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
Guide FableLoom from story plan to 16:9 delivery (#5518)
[._.]/ Adam Eivy689006bc21af
diff --git a/client/src/components/fableloom/LoomContinuityPanel.jsx b/client/src/components/fableloom/LoomContinuityPanel.jsxnew file mode 100644index 0000000000..a7623e39b2--- /dev/null+++ b/client/src/components/fableloom/LoomContinuityPanel.jsx@@ -0,0 +1,123 @@+import { useState } from 'react';+import {+ AlertTriangle, CheckCircle2, CircleAlert, Film, Info, Loader2, Sparkles,+} from 'lucide-react';+import { useAsyncAction } from '../../hooks/useAsyncAction';+import { reviewLoomEpisodeContinuity } from '../../services/api';++const severityIcon = (severity) => {+ if (severity === 'error' || severity === 'high') {+ return <CircleAlert size={14} className="mt-0.5 shrink-0 text-port-error" />;+ }+ if (severity === 'warning') {+ return <AlertTriangle size={14} className="mt-0.5 shrink-0 text-port-warning" />;+ }+ return <Info size={14} className="mt-0.5 shrink-0 text-port-accent" />;+};++export default function LoomContinuityPanel({+ loom,+ episode,+ review,+ onReviewChange,+ onSelectNode,+}) {+ const [categoryFilter, setCategoryFilter] = useState('all');+ const [runReview, reviewing] = useAsyncAction(async () => {+ const requestedEpisodeId = episode.id;+ const result = await reviewLoomEpisodeContinuity(loom.id, requestedEpisodeId, {}, { silent: true });+ onReviewChange(requestedEpisodeId, result);+ }, { errorMessage: 'Continuity review failed' });+ const findings = (review?.findings || []).filter((finding) => (+ categoryFilter === 'all' || finding.category === categoryFilter+ ));++ return (+ <section className="space-y-4" aria-label="Continuity review">+ <header>+ <h3 className="flex items-center gap-1.5 text-sm font-semibold">+ <Film size={14} className="text-port-accent" />+ Continuity & canon+ </h3>+ <p className="mt-1 text-xs text-port-text-muted">+ Run this after story and path review, before render settings. It checks character visuals, wardrobe, voice, pronunciation, playback, and convergence sources.+ </p>+ </header>++ <button+ type="button"+ onClick={runReview}+ disabled={reviewing}+ className="flex min-h-11 w-full items-center justify-center gap-2 rounded bg-port-accent px-3 py-2 text-sm font-medium text-white disabled:opacity-50"+ >+ {reviewing ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}+ {reviewing ? 'Reviewing continuity…' : review ? 'Run continuity review again' : 'Run continuity review'}+ </button>++ {review ? (+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-3 text-xs">+ <span className={`flex items-center gap-1 font-medium ${review.passed ? 'text-port-success' : 'text-port-error'}`}>+ {review.passed ? <CheckCircle2 size={13} /> : <CircleAlert size={13} />}+ {review.passed+ ? 'All continuity checks passed'+ : `${review.summary?.errors || 0} error(s), ${review.summary?.warnings || 0} warning(s)`}+ </span>+ <span className="shrink-0 text-[11px] text-port-text-muted">{review.nodesEvaluated} scenes</span>+ </div>++ <div className="flex gap-1 overflow-x-auto pb-1 text-[11px]" role="group" aria-label="Continuity category">+ {['all', 'visual', 'voice', 'playback', 'graph'].map((category) => (+ <button+ key={category}+ type="button"+ aria-pressed={categoryFilter === category}+ onClick={() => setCategoryFilter(category)}+ className={`rounded px-2 py-1 capitalize ${+ categoryFilter === category+ ? 'bg-port-accent font-medium text-white'+ : 'border border-port-border bg-port-card text-port-text-muted hover:text-port-text'+ }`}+ >+ {category}+ </button>+ ))}+ </div>++ {findings.length ? (+ <div className="space-y-1.5">+ {findings.map((finding) => (+ <button+ key={finding.id}+ type="button"+ onClick={() => finding.nodeId && onSelectNode?.(finding.nodeId)}+ disabled={!finding.nodeId}+ className={`flex w-full items-start gap-2 rounded border border-port-border p-2 text-left text-xs ${+ finding.nodeId ? 'cursor-pointer hover:border-port-accent' : 'cursor-default'+ }`}+ >+ {severityIcon(finding.severity)}+ <span className="min-w-0 flex-1">+ <span className="font-medium text-port-text">{finding.message}</span>+ {finding.remediation ? (+ <span className="mt-0.5 block text-[11px] text-port-text-muted">Fix: {finding.remediation}</span>+ ) : null}+ {finding.nodeId ? (+ <span className="mt-1 block text-[10px] text-port-accent">Open affected scene</span>+ ) : null}+ </span>+ </button>+ ))}+ </div>+ ) : (+ <p className="text-xs text-port-text-muted">No {categoryFilter === 'all' ? '' : categoryFilter} continuity issues found.</p>+ )}+ </div>+ ) : (+ <p className="rounded border border-port-border bg-port-bg/30 p-3 text-xs text-port-text-muted">+ No continuity review has run for this episode yet.+ </p>+ )}+ </section>+ );+}diff --git a/client/src/components/fableloom/LoomContinuityPanel.test.jsx b/client/src/components/fableloom/LoomContinuityPanel.test.jsxnew file mode 100644index 0000000000..f8542f3600--- /dev/null+++ b/client/src/components/fableloom/LoomContinuityPanel.test.jsx@@ -0,0 +1,58 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import * as api from '../../services/api';+import LoomContinuityPanel from './LoomContinuityPanel';++vi.mock('../../services/api');++describe('LoomContinuityPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.reviewLoomEpisodeContinuity.mockResolvedValue({+ passed: false,+ nodesEvaluated: 3,+ summary: { errors: 1, warnings: 0, info: 0 },+ findings: [{+ id: 'finding-1', category: 'visual', severity: 'error',+ message: 'Character binding is missing', remediation: 'Bind the canonical character.', nodeId: 'scene-1',+ }],+ });+ });++ it('runs separately from rendering and returns review state to the workflow owner', async () => {+ const user = userEvent.setup();+ const onReviewChange = vi.fn();+ const onSelectNode = vi.fn();+ const { rerender } = render(+ <LoomContinuityPanel+ loom={{ id: 'loom-1' }}+ episode={{ id: 'episode-1' }}+ review={null}+ onReviewChange={onReviewChange}+ onSelectNode={onSelectNode}+ />,+ );++ await user.click(screen.getByRole('button', { name: 'Run continuity review' }));+ await waitFor(() => expect(onReviewChange).toHaveBeenCalledWith(+ 'episode-1',+ expect.objectContaining({ passed: false }),+ ));+ const review = onReviewChange.mock.calls[0][1];+ rerender(+ <LoomContinuityPanel+ loom={{ id: 'loom-1' }}+ episode={{ id: 'episode-1' }}+ review={review}+ onReviewChange={onReviewChange}+ onSelectNode={onSelectNode}+ />,+ );++ expect(screen.getByText('Character binding is missing')).toBeInTheDocument();+ expect(screen.getByText('Fix: Bind the canonical character.')).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: /Character binding is missing/i }));+ expect(onSelectNode).toHaveBeenCalledWith('scene-1');+ });+});diff --git a/client/src/components/fableloom/LoomEditorialAutomation.jsx b/client/src/components/fableloom/LoomEditorialAutomation.jsxindex 29324d6d50..e9856db254 100644--- a/client/src/components/fableloom/LoomEditorialAutomation.jsx+++ b/client/src/components/fableloom/LoomEditorialAutomation.jsx@@ -200,6 +200,16 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {const passed = result?.type === 'playtest'? response?.passed: shownRun?.status === 'completed' || diagnostics?.passed;+ const resultHeading = passed+ ? 'Series clears the current editorial gates'+ : shownRun?.status === 'failed'+ ? 'Editorial automation needs attention'+ : shownRun?.status === 'canceled'+ ? 'Editorial autopilot stopped'+ : 'Editorial work remains';+ const restartLabel = ['failed', 'paused', 'canceled'].includes(shownRun?.status)+ ? 'Retry editor autopilot'+ : 'Start editor autopilot';return (<section@@ -212,12 +222,14 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {<BrainCircuit size={16} className="text-port-accent" /> AI editor, reviewer & playtest</h3><p className="mt-1 text-xs text-port-text-muted max-w-3xl">- One editor can evaluate and safely repair the complete series. Autopilot alternates that editor with an independent review of every enumerated gameplay path until the story passes or reaches its bounded round limit.+ One editor can evaluate and safely repair the complete series. Autopilot alternates that editor with an independent review of every enumerated gameplay path until the story passes or reaches its bounded round limit. Rejected graph patches are corrected with validator feedback before a run can fail.</p></div>{shownRun ? (<span className={`shrink-0 rounded border px-2 py-1 text-xs ${statusClass(shownRun.status)}`}>- {shownRun.status} · round {shownRun.round}/{shownRun.maxRounds}+ {shownRun.status}+ {shownRun.stepIndex ? ` · step ${shownRun.stepIndex}/${shownRun.stepCount}` : ''}+ {` · round ${shownRun.round}/${shownRun.maxRounds}`}</span>) : null}</div>@@ -320,7 +332,7 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {className="flex min-h-11 items-center justify-center gap-2 rounded border border-port-accent px-3 py-2 text-sm text-port-accent hover:bg-port-accent/10 disabled:opacity-50">{startingAutopilot ? <Loader2 size={14} className="animate-spin" /> : <BrainCircuit size={14} />}- {startingAutopilot ? 'Starting…' : 'Start editor autopilot'}+ {startingAutopilot ? 'Starting…' : restartLabel}</button>)}</div>@@ -349,7 +361,7 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {)}<div><p className="text-sm font-medium">- {passed ? 'Series clears the current editorial gates' : 'Editorial work remains'}+ {resultHeading}</p>{summary ? <p className="mt-1 text-xs text-port-text-muted">{summary}</p> : null}</div>@@ -398,6 +410,13 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {{shownRun.rounds.length} bounded editorial round{shownRun.rounds.length === 1 ? '' : 's'} recorded. The run stops on success, plateau, cancellation, provider failure, or the selected round limit.</p>) : null}+ {shownRun?.invalidResponses ? (+ <p className="text-[11px] text-port-text-muted">+ {shownRun.status === 'failed'+ ? `Autopilot safely rejected ${shownRun.invalidResponses} invalid editor responses; no invalid changes were applied.`+ : `Autopilot safely rejected and retried ${shownRun.invalidResponses} invalid editor response${shownRun.invalidResponses === 1 ? '' : 's'} before continuing.`}+ </p>+ ) : null}{shownRun?.selfImprove?.verdict === 'pipeline' ? (<div className="rounded border border-port-accent/30 bg-port-accent/5 px-3 py-2 text-xs text-port-accent"><p>diff --git a/client/src/components/fableloom/LoomEditorialAutomation.test.jsx b/client/src/components/fableloom/LoomEditorialAutomation.test.jsxindex 00facc3bd8..d42ea044bc 100644--- a/client/src/components/fableloom/LoomEditorialAutomation.test.jsx+++ b/client/src/components/fableloom/LoomEditorialAutomation.test.jsx@@ -113,7 +113,8 @@ describe('LoomEditorialAutomation', () => {const user = userEvent.setup();api.startLoomEditorialAutopilot.mockResolvedValue({id: 'editorial-run-1', loomId: 'loom-1', status: 'running', round: 1, maxRounds: 3,- message: 'Round 1: evaluating and remediating the complete series…', rounds: [],+ stepIndex: 1, stepCount: 6,+ message: 'Step 1 of up to 6 · round 1: evaluating and remediating the complete series…', rounds: [],residualFindings: [],});renderPanel();@@ -124,7 +125,25 @@ describe('LoomEditorialAutomation', () => {'loom-1', { maxRounds: 3 }, { silent: true },));expect(screen.getByRole('button', { name: 'Stop editor autopilot' })).toBeInTheDocument();- expect(screen.getAllByText(/Round 1: evaluating and remediating/).length).toBeGreaterThan(0);+ expect(screen.getAllByText(/step 1 of up to 6/i).length).toBeGreaterThan(0);+ expect(screen.getByText(/running · step 1\/6 · round 1\/3/i)).toBeInTheDocument();+ });++ it('explains a failed automation as a retryable system outcome', async () => {+ api.getLoom.mockResolvedValue(loom);+ api.getLoomEditorialAutopilotStatus.mockResolvedValue({+ run: {+ id: 'editorial-run-1', loomId: 'loom-1', status: 'failed', round: 1, maxRounds: 3,+ stepIndex: 1, stepCount: 6, responseCorrections: 2, invalidResponses: 3,+ message: 'Editorial autopilot could not obtain a graph-safe editor patch after 3 attempts.',+ rounds: [], residualFindings: [],+ },+ });+ renderPanel();++ expect(await screen.findByText('Editorial automation needs attention')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Retry editor autopilot' })).toBeInTheDocument();+ expect(screen.getByText(/safely rejected 3 invalid editor responses; no invalid changes were applied/i)).toBeInTheDocument();});it('opts a run into approval-gated FableLoom workflow diagnosis', async () => {diff --git a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsxindex 46fd4f1a39..77da8793bb 100644--- a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx+++ b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx@@ -15,8 +15,18 @@ import {import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providers';import { fieldClass, labelClass } from './fieldStyles';import LoomAiRunStatus from './LoomAiRunStatus';+import {+ FABLELOOM_CHALLENGE_PHASES,+ fableLoomPlotPointKind,+} from '../../../../server/lib/fableLoomOutline.js';const asArray = (value) => (Array.isArray(value) ? value : []);+const TELEPLAY_SYNC_ISSUE_CODES = new Set([+ 'TELEPLAY_SCENE_MEMBERSHIP_MISMATCH',+ 'TELEPLAY_START_MISMATCH',+ 'TELEPLAY_SCENE_CONTRACT_MISMATCH',+]);+const isTeleplaySyncIssue = (issue) => TELEPLAY_SYNC_ISSUE_CODES.has(issue?.code);const cloneOutline = (outline) => (outline ? {...outline,@@ -31,14 +41,21 @@ const cloneOutline = (outline) => (outline ? {const draftValidation = { status: 'draft', issues: [] };-function ValidationResult({ validation }) {+function ValidationResult({ validation, teleplayReplacementReady = false }) {if (!validation) return null;const issues = asArray(validation.issues);- const hasErrors = issues.some((issue) => issue.severity !== 'warning');+ const hasErrors = !teleplayReplacementReady+ && issues.some((issue) => issue.severity !== 'warning');const status = validation.stats? (validation.stats.errorCount ? 'invalid' : 'valid'): validation.status || 'draft';- const label = status === 'valid' ? 'Outline is structurally valid' : status === 'invalid' ? 'Outline needs edits' : 'Outline is a draft';+ const label = teleplayReplacementReady+ ? 'Outline is ready to replace the old teleplay'+ : status === 'valid'+ ? 'Outline is structurally valid'+ : status === 'invalid'+ ? 'Outline needs edits'+ : 'Outline is a draft';return (<div className={`rounded border p-3 space-y-2 ${status === 'valid' ? 'border-port-success/40 bg-port-success/5' : hasErrors ? 'border-port-error/40 bg-port-error/5' : 'border-port-warning/40 bg-port-warning/5'}`} aria-live="polite"><div className="flex items-center gap-2 text-sm font-semibold">@@ -51,7 +68,7 @@ function ValidationResult({ validation }) {{issues.length ? (<ul className="space-y-1 text-xs text-port-text-muted">{issues.map((issue, index) => <li key={`${issue.code || 'issue'}-${issue.sceneKey || 'outline'}-${index}`} className="flex items-start gap-1.5">- {issue.severity === 'warning' ? <AlertTriangle size={12} className="mt-0.5 shrink-0 text-port-warning" /> : <CircleAlert size={12} className="mt-0.5 shrink-0 text-port-error" />}+ {issue.severity === 'warning' || teleplayReplacementReady ? <AlertTriangle size={12} className="mt-0.5 shrink-0 text-port-warning" /> : <CircleAlert size={12} className="mt-0.5 shrink-0 text-port-error" />}<span>{issue.message}</span></li>)}</ul>@@ -62,8 +79,11 @@ function ValidationResult({ validation }) {);}-function OutlineBeat({ scene, index, scenes, onChange, onRemovePath, onAddPath, expanded, onToggle }) {+function OutlineBeat({+ scene, index, scenes, plotPoints, onChange, onRemovePath, onAddPath, expanded, onToggle,+}) {const possibleTargets = scenes.filter((candidate) => candidate.key !== scene.key);+ const selectedPlotPoint = plotPoints.find((item) => item.id === scene.plotPointId) || null;return (<article className="rounded-lg border border-port-border bg-port-bg/40" data-testid={`outline-beat-${scene.key}`}><button@@ -77,6 +97,11 @@ function OutlineBeat({ scene, index, scenes, onChange, onRemovePath, onAddPath,<span className="min-w-0"><span className="block break-words text-sm font-semibold">{scene.title || 'Untitled beat'}</span><span className="mt-1 block break-words text-xs text-port-text-muted">{scene.summary || 'No log-line yet.'}</span>+ {scene.challengePhase ? (+ <span className="mt-1 inline-flex rounded bg-port-accent/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-port-accent">+ {scene.challengePhase}+ </span>+ ) : null}</span></span>{expanded ? <ChevronUp size={15} className="shrink-0 text-port-text-muted" /> : <ChevronDown size={15} className="shrink-0 text-port-text-muted" />}@@ -98,6 +123,46 @@ function OutlineBeat({ scene, index, scenes, onChange, onRemovePath, onAddPath,onChange={(event) => onChange({ summary: event.target.value })}/></FormField>+ {plotPoints.length ? (+ <div className="grid gap-2 sm:grid-cols-2">+ <FormField label="Mapped plot point" labelClassName={labelClass} hint="Connect this beat to the durable series-plan item it realizes.">+ <select+ className={fieldClass}+ value={scene.plotPointId || ''}+ onChange={(event) => {+ const plotPointId = event.target.value || null;+ const selected = plotPoints.find((item) => item.id === plotPointId);+ onChange({+ plotPointId,+ challengePhase: fableLoomPlotPointKind(selected) === 'challenge'+ ? scene.challengePhase || 'setup'+ : null,+ });+ }}+ >+ <option value="">Not mapped</option>+ {plotPoints.map((item) => (+ <option key={item.id} value={item.id}>+ {fableLoomPlotPointKind(item) === 'challenge' ? 'Challenge: ' : ''}{item.title || 'Untitled plot point'}+ </option>+ ))}+ </select>+ </FormField>+ {fableLoomPlotPointKind(selectedPlotPoint) === 'challenge' ? (+ <FormField label="Challenge phase" labelClassName={labelClass} hint="Every challenge needs all five phases before validation passes.">+ <select+ className={fieldClass}+ value={scene.challengePhase || 'setup'}+ onChange={(event) => onChange({ challengePhase: event.target.value })}+ >+ {FABLELOOM_CHALLENGE_PHASES.map((phase) => (+ <option key={phase} value={phase}>{phase[0].toUpperCase() + phase.slice(1)}</option>+ ))}+ </select>+ </FormField>+ ) : null}+ </div>+ ) : null}<div className="grid grid-cols-2 gap-2"><label className={labelClass}>Playback@@ -198,11 +263,22 @@ export default function LoomEpisodeOutlinePlanner({}, [episode.id]);const scenes = asArray(outline?.scenes);+ const plotPoints = asArray(loom.seriesPlan?.plotPoints)+ .filter((item) => item.episodeId === episode.id);const outlineStatus = validation?.stats? (validation.stats.errorCount ? 'invalid' : 'valid'): outline?.validation?.status || 'draft';const busy = disabled || providersLoading || generateRun.run?.phase === 'running' || reviewRun.run?.phase === 'running';const hasScenes = episode.nodes.length > 0;+ const activeValidation = validation || outline?.validation;+ const activeValidationIssues = asArray(activeValidation?.issues);+ const replacementBlockingIssues = activeValidationIssues+ .filter((issue) => issue.severity !== 'warning');+ const teleplayReplacementReady = hasScenes+ && outlineStatus === 'invalid'+ && replacementBlockingIssues.length > 0+ && replacementBlockingIssues.every(isTeleplaySyncIssue);+ const canExpand = outlineStatus === 'valid' || teleplayReplacementReady;const updateOutline = (updater) => {setOutline((current) => {@@ -328,6 +404,7 @@ export default function LoomEpisodeOutlinePlanner({scene={scene}index={index}scenes={scenes}+ plotPoints={plotPoints}expanded={expandedKey === scene.key}onToggle={() => setExpandedKey((current) => current === scene.key ? null : scene.key)}onChange={(patch) => updateBeat(scene.key, patch)}@@ -355,16 +432,23 @@ export default function LoomEpisodeOutlinePlanner({</button></div>{dirty ? <p className="text-xs text-port-warning">Save the edited log-lines before asking the AI to review them.</p> : null}- <ValidationResult validation={validation || outline.validation} />+ <ValidationResult+ validation={activeValidation}+ teleplayReplacementReady={teleplayReplacementReady}+ />{onExpand ? (<buttontype="button"onClick={onExpand}- disabled={busy || dirty || outlineStatus !== 'valid' || saving || generating || validating || reviewing || expanding}+ disabled={busy || dirty || !canExpand || saving || generating || validating || reviewing || expanding}className="flex w-full items-center justify-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50">{expanding ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}- {expanding ? 'Expanding validated outline…' : 'Expand validated outline to teleplay'}+ {expanding+ ? 'Expanding validated outline…'+ : teleplayReplacementReady+ ? 'Replace old teleplay from this outline'+ : 'Expand validated outline to teleplay'}</button>) : null}{review ? (diff --git a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsxindex db83648b24..c450d10dce 100644--- a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx+++ b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx@@ -74,4 +74,82 @@ describe('LoomEpisodeOutlinePlanner', () => {expect(api.validateLoomEpisodeOutline).toHaveBeenCalledWith('loom-1', 'ep-1', { silent: true });expect(await screen.findByText('Outline is structurally valid')).toBeInTheDocument();});++ it('offers to replace an older teleplay when only outline-to-scene sync is invalid', async () => {+ const user = userEvent.setup();+ const onExpand = vi.fn();+ const replacementOutline = {+ ...outline,+ validation: {+ status: 'invalid',+ issues: [{+ code: 'TELEPLAY_SCENE_CONTRACT_MISMATCH',+ severity: 'error',+ message: 'The revised beat no longer matches the old teleplay scene contract.',+ sceneKey: 's1',+ }],+ },+ };+ const expandedEpisode = {+ ...episode,+ nodes: [{ id: 's1', title: 'Old scene' }],+ storyOutline: replacementOutline,+ };++ render(+ <LoomEpisodeOutlinePlanner+ open+ loom={loom}+ episode={expandedEpisode}+ onLoomUpdate={vi.fn()}+ onExpand={onExpand}+ />,+ );++ expect(screen.getByText('Outline is ready to replace the old teleplay')).toBeInTheDocument();+ const replace = screen.getByRole('button', { name: 'Replace old teleplay from this outline' });+ expect(replace).toBeEnabled();+ await user.click(replace);+ expect(onExpand).toHaveBeenCalledTimes(1);+ });++ it('maps a playable challenge and its production phase onto a concrete beat', async () => {+ const user = userEvent.setup();+ const challengeLoom = {+ ...loom,+ seriesPlan: {+ plotPoints: [{+ id: 'plot-lock', kind: 'challenge', title: 'Open the sealed door',+ description: 'Recall the planted code.', episodeId: 'ep-1',+ }],+ },+ };+ api.updateLoomEpisode.mockImplementation(async (_loomId, _episodeId, patch) => ({+ ...challengeLoom,+ episodes: [{ ...episode, storyOutline: patch.storyOutline }],+ }));+ render(+ <LoomEpisodeOutlinePlanner+ open loom={challengeLoom} episode={episode} onLoomUpdate={vi.fn()}+ />,+ );++ await user.click(screen.getByTestId('outline-beat-s1').querySelector('button'));+ await user.selectOptions(screen.getByLabelText('Mapped plot point'), 'plot-lock');+ await user.selectOptions(screen.getByLabelText('Challenge phase'), 'failure');+ await user.click(screen.getByRole('button', { name: 'Save outline' }));++ await waitFor(() => expect(api.updateLoomEpisode).toHaveBeenCalledWith(+ 'loom-1',+ 'ep-1',+ expect.objectContaining({+ storyOutline: expect.objectContaining({+ scenes: expect.arrayContaining([expect.objectContaining({+ key: 's1', plotPointId: 'plot-lock', challengePhase: 'failure',+ })]),+ }),+ }),+ { silent: true },+ ));+ });});diff --git a/client/src/components/fableloom/LoomProductionPanel.jsx b/client/src/components/fableloom/LoomProductionPanel.jsxindex 4afa39c2a9..41fb4784f1 100644--- a/client/src/components/fableloom/LoomProductionPanel.jsx+++ b/client/src/components/fableloom/LoomProductionPanel.jsx@@ -1,18 +1,18 @@/**- * FableLoom production orchestration and episodic continuity review panel.+ * FableLoom render orchestration panel.** Provides user-triggered batch production planning, DAG asset enumeration,- * exact-input verification, batch execution tracking, and episodic continuity review.+ * exact-input verification, and batch execution tracking. Continuity review+ * lives in its own workflow tab so a producer never has to hunt below render settings.*/-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import {AlertTriangle,CheckCircle2,CircleAlert,Cloud,Cpu,- Film,Info,Layers,Loader2,@@ -29,11 +29,15 @@ import {listImageModels,listVideoModels,planLoomEpisodeProduction,- reviewLoomEpisodeContinuity,resumeLoomEpisodeProductionBatch,startLoomEpisodeProductionBatch,+ updateLoom,} from '../../services/api';import { fableLoomStoryReadiness } from '../../lib/fableLoomReadiness';+import {+ asFableLoomRenderSettings,+ FABLELOOM_RENDER_FORMATS,+} from '../../../../server/lib/fableLoomProduction.js';const IMAGE_BACKENDS = [{ id: 'auto', label: 'Auto', icon: Layers },@@ -61,23 +65,12 @@ const productionAssetsForScope = (plan, scope) => {const assetIsReady = (asset) => asset.status !== 'blocked' && asset.readiness?.ready !== false;-const severityIcon = (severity) => {- if (severity === 'error' || severity === 'high') {- return <CircleAlert size={14} className="text-port-error shrink-0 mt-0.5" />;- }- if (severity === 'warning') {- return <AlertTriangle size={14} className="text-port-warning shrink-0 mt-0.5" />;- }- return <Info size={14} className="text-port-accent shrink-0 mt-0.5" />;-};--export default function LoomProductionPanel({ loom, episode, onSelectNode }) {+export default function LoomProductionPanel({ loom, episode, onSelectNode, onLoomUpdate }) {const [mode, setMode] = useState('current_canon');const [assetScope, setAssetScope] = useState('images');const [plan, setPlan] = useState(null);+ const [planKey, setPlanKey] = useState(null);const [activeBatchRun, setActiveBatchRun] = useState(null);- const [continuityReview, setContinuityReview] = useState(null);- const [categoryFilter, setCategoryFilter] = useState('all');const [imageMode, setImageMode] = useState(null);const [imageModel, setImageModel] = useState(null);const [videoMode, setVideoMode] = useState(null);@@ -85,6 +78,24 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {const [effort, setEffort] = useState(null);const [imageModels, setImageModels] = useState([]);const [videoModels, setVideoModels] = useState([]);+ const renderFormat = asFableLoomRenderSettings(loom.renderSettings);+ const productionIdentity = `${loom.id}:${episode.id}`;+ const productionIdentityRef = useRef(productionIdentity);+ productionIdentityRef.current = productionIdentity;+ const planInputKey = JSON.stringify({+ loomId: loom.id,+ episodeId: episode.id,+ formatId: renderFormat.formatId,+ mode,+ imageMode,+ imageModel,+ videoMode,+ videoModel,+ effort,+ });+ const planInputKeyRef = useRef(planInputKey);+ planInputKeyRef.current = planInputKey;+ const planRequestRef = useRef(0);const renderOptions = (targetMode = mode) => ({mode: targetMode,@@ -96,10 +107,35 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {});const [fetchPlan, planning] = useAsyncAction(async (targetMode = mode) => {- const res = await planLoomEpisodeProduction(loom.id, episode.id, renderOptions(targetMode), { silent: true });+ const requestId = planRequestRef.current + 1;+ planRequestRef.current = requestId;+ const requestKey = JSON.stringify({+ loomId: loom.id,+ episodeId: episode.id,+ formatId: renderFormat.formatId,+ mode: targetMode,+ imageMode,+ imageModel,+ videoMode,+ videoModel,+ effort,+ });+ const res = await planLoomEpisodeProduction(+ loom.id,+ episode.id,+ renderOptions(targetMode),+ { silent: true },+ );+ if (planRequestRef.current !== requestId || planInputKeyRef.current !== requestKey) return;setPlan(res);+ setPlanKey(requestKey);}, { errorMessage: 'Production planning failed' });+ const [saveRenderFormat, savingRenderFormat] = useAsyncAction(async (formatId) => {+ const updated = await updateLoom(loom.id, { renderSettings: { formatId } }, { silent: true });+ onLoomUpdate?.(updated);+ }, { errorMessage: 'Saving output format failed' });+useEffect(() => {const load = (loader) => (typeof loader === 'function'? Promise.resolve().then(() => loader({ silent: true })).catch(() => [])@@ -114,16 +150,28 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {}, []);useEffect(() => {+ setPlan(null);+ setPlanKey(null);fetchPlan(mode);- }, [loom.id, episode.id, mode, imageMode, imageModel, videoMode, videoModel, effort]);+ }, [planInputKey]);++ useEffect(() => {+ setActiveBatchRun(null);+ }, [productionIdentity]);// Batch run pollinguseEffect(() => {if (!activeBatchRun || activeBatchRun.status !== 'in_progress') return undefined;const interval = setInterval(() => {- getLoomEpisodeProductionBatch(loom.id, episode.id, activeBatchRun.id, { silent: true })+ getLoomEpisodeProductionBatch(+ activeBatchRun.loomId,+ activeBatchRun.episodeId,+ activeBatchRun.id,+ { silent: true },+ ).then((updated) => {if (!updated) return;+ if (`${updated.loomId}:${updated.episodeId}` !== productionIdentityRef.current) return;setActiveBatchRun(updated);if (updated.status === 'completed' || updated.status === 'canceled' || updated.status === 'failed') {fetchPlan(mode);@@ -134,33 +182,39 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {});}, 2000);return () => clearInterval(interval);- }, [activeBatchRun, loom.id, episode.id, mode]);+ }, [activeBatchRun, mode]);const [startBatch, startingBatch] = useAsyncAction(async () => {+ const requestedIdentity = productionIdentity;const res = await startLoomEpisodeProductionBatch(loom.id, episode.id, {...renderOptions(),...(selectedAssetTypes ? { assetTypes: selectedAssetTypes } : {}),}, { silent: true });- setActiveBatchRun(res);+ if (productionIdentityRef.current === requestedIdentity) setActiveBatchRun(res);}, { errorMessage: 'Starting production batch failed' });const [cancelBatch, cancelingBatch] = useAsyncAction(async () => {if (!activeBatchRun) return;- const res = await cancelLoomEpisodeProductionBatch(loom.id, episode.id, activeBatchRun.id, { silent: true });- setActiveBatchRun(res);+ const res = await cancelLoomEpisodeProductionBatch(+ activeBatchRun.loomId,+ activeBatchRun.episodeId,+ activeBatchRun.id,+ { silent: true },+ );+ if (`${res.loomId}:${res.episodeId}` === productionIdentityRef.current) setActiveBatchRun(res);}, { errorMessage: 'Canceling batch run failed' });const [resumeBatch, resumingBatch] = useAsyncAction(async () => {if (!activeBatchRun) return;- const res = await resumeLoomEpisodeProductionBatch(loom.id, episode.id, activeBatchRun.id, { silent: true });- setActiveBatchRun(res);+ const res = await resumeLoomEpisodeProductionBatch(+ activeBatchRun.loomId,+ activeBatchRun.episodeId,+ activeBatchRun.id,+ { silent: true },+ );+ if (`${res.loomId}:${res.episodeId}` === productionIdentityRef.current) setActiveBatchRun(res);}, { errorMessage: 'Resuming batch run failed' });- const [runContinuityReview, reviewingContinuity] = useAsyncAction(async () => {- const res = await reviewLoomEpisodeContinuity(loom.id, episode.id, {}, { silent: true });- setContinuityReview(res);- }, { errorMessage: 'Continuity review failed' });-const scopedAssets = productionAssetsForScope(plan, assetScope);const hasAssetList = Array.isArray(plan?.plannedAssets);const plannedCount = hasAssetList@@ -178,11 +232,6 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {const selectedAssetTypes = assetScope === 'images' ? ['image'] : null;const storyReadiness = fableLoomStoryReadiness(loom);- const filteredFindings = (continuityReview?.findings || []).filter((f) => {- if (categoryFilter === 'all') return true;- return f.category === categoryFilter;- });-const readinessBlockers = [...(episode?.nodes?.length && !storyReadiness.ready? [{ message: storyReadiness.reason, nodeId: null }]@@ -198,10 +247,13 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {candidate.message === item.message && candidate.nodeId === item.nodeId)) === index);const canStart = readinessBlockers.length === 0- && (mode !== 'exact_inputs' || !plan?.exactInputIssues?.length);+ && (mode !== 'exact_inputs' || !plan?.exactInputIssues?.length)+ && planKey === planInputKey+ && !planning+ && !savingRenderFormat;return (- <div className="p-4 space-y-6">+ <div className="space-y-6">{/* 1. Production Mode & Plan Summary */}<div><div className="flex items-center justify-between mb-2">@@ -316,6 +368,28 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {<div className="rounded bg-port-card border border-port-border p-2.5 space-y-2"><div className="text-[10px] uppercase font-semibold text-port-text-muted">Render settings</div><div className="space-y-1.5">+ <div className="flex flex-wrap items-center gap-2">+ <label htmlFor="fableloom-render-format" className="text-[11px] text-port-text-muted w-14">Output</label>+ <select+ id="fableloom-render-format"+ value={renderFormat.formatId}+ onChange={(event) => saveRenderFormat(event.target.value)}+ disabled={savingRenderFormat}+ className="text-[11px] bg-port-bg border border-port-border rounded px-1.5 py-1 text-port-text disabled:opacity-50"+ >+ {FABLELOOM_RENDER_FORMATS.map((format) => (+ <option key={format.formatId} value={format.formatId}>+ {format.label} · {format.width}×{format.height}+ </option>+ ))}+ </select>+ {savingRenderFormat && <Loader2 size={11} className="animate-spin text-port-text-muted" aria-label="Saving output format" />}+ <span className="text-[10px] text-port-text-muted">+ {mode === 'exact_inputs'+ ? 'Exact-input mode preserves each asset’s recorded dimensions.'+ : 'Shared by storyboard images and video clips; 16:9 landscape is the default.'}+ </span>+ </div><div className="flex flex-wrap items-center gap-2"><span className="text-[11px] text-port-text-muted w-14">Images</span><BackendChipStrip@@ -388,6 +462,29 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {</div></div>+ {plan.formatMismatches?.length > 0 && (+ <div className="p-2.5 rounded bg-port-warning/10 border border-port-warning/30 text-xs space-y-1">+ <div className="font-semibold flex items-center gap-1 text-port-warning">+ <AlertTriangle size={12} />+ Existing media uses another aspect ratio+ </div>+ <p className="text-[11px] text-port-text-muted pl-4">+ {plan.formatMismatches.length} media asset(s) will be regenerated at{' '}+ {renderFormat.aspectRatio} ({renderFormat.width}×{renderFormat.height}).+ </p>+ {plan.formatMismatches.map((mismatch) => (+ <button+ key={mismatch.assetId || `${mismatch.nodeId}-${mismatch.assetType || 'media'}`}+ type="button"+ onClick={() => onSelectNode?.(mismatch.nodeId)}+ className="block w-full text-left text-[11px] text-port-text-muted pl-4 hover:text-port-text"+ >+ {mismatch.nodeTitle || mismatch.nodeId} · {(mismatch.assetType || 'media').replaceAll('_', ' ')}: {mismatch.actualWidth}×{mismatch.actualHeight} → {mismatch.expectedAspectRatio}+ </button>+ ))}+ </div>+ )}+{readinessBlockers.length > 0 && (<div className="p-2.5 rounded bg-port-warning/10 border border-port-warning/30 text-xs space-y-1"><div className="font-semibold flex items-center gap-1 text-port-warning">@@ -481,7 +578,7 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {<buttontype="button"onClick={startBatch}- disabled={startingBatch || !canStart}+ disabled={startingBatch || savingRenderFormat || !canStart}className="flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50">{startingBatch ? <Loader2 size={12} className="animate-spin" /> : <Play size={12} />}@@ -543,96 +640,6 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode }) {)}</div>- {/* 2. Episodic Continuity Review */}- <div className="border-t border-port-border pt-4">- <div className="flex items-center justify-between mb-2">- <h3 className="text-sm font-semibold flex items-center gap-1.5">- <Film size={14} className="text-port-accent" />- Continuity Review- </h3>- <button- type="button"- onClick={runContinuityReview}- disabled={reviewingContinuity}- className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50 font-medium"- >- {reviewingContinuity ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}- Run Continuity Review- </button>- </div>-- {continuityReview ? (- <div className="space-y-3">- <div className="flex items-center justify-between text-xs">- <span className={continuityReview.passed ? 'text-port-success font-medium flex items-center gap-1' : 'text-port-error font-medium flex items-center gap-1'}>- {continuityReview.passed ? <CheckCircle2 size={13} /> : <CircleAlert size={13} />}- {continuityReview.passed ? 'All continuity checks passed' : `${continuityReview.summary?.errors || 0} error(s), ${continuityReview.summary?.warnings || 0} warning(s)`}- </span>- <span className="text-port-text-muted text-[11px]">- {continuityReview.nodesEvaluated} scenes evaluated- </span>- </div>-- {/* Category filter pills */}- <div className="flex gap-1 overflow-x-auto pb-1 text-[11px]">- {['all', 'visual', 'voice', 'playback', 'graph'].map((cat) => (- <button- key={cat}- type="button"- onClick={() => setCategoryFilter(cat)}- className={`px-2 py-0.5 rounded capitalize ${- categoryFilter === cat- ? 'bg-port-accent text-white font-medium'- : 'bg-port-card border border-port-border text-port-text-muted hover:text-port-text'- }`}- >- {cat}- </button>- ))}- </div>-- {/* Findings list */}- {filteredFindings.length > 0 ? (- <div className="space-y-1.5">- {filteredFindings.map((finding) => (- <button- key={finding.id}- type="button"- onClick={() => finding.nodeId && onSelectNode && onSelectNode(finding.nodeId)}- disabled={!finding.nodeId}- className={`w-full text-left flex items-start gap-2 text-xs rounded p-2 border border-port-border ${- finding.nodeId ? 'hover:border-port-accent cursor-pointer' : 'cursor-default'- }`}- >- {severityIcon(finding.severity)}- <div className="flex-1">- <div className="font-medium text-port-text">{finding.message}</div>- {finding.remediation && (- <div className="text-[11px] text-port-text-muted mt-0.5">- Remediation: {finding.remediation}- </div>- )}- {finding.nodeId && (- <div className="text-[10px] text-port-accent mt-1">- Jump to scene [{finding.nodeId}]- </div>- )}- </div>- </button>- ))}- </div>- ) : (- <p className="text-xs text-port-text-muted">- No {categoryFilter === 'all' ? '' : categoryFilter} continuity issues found.- </p>- )}- </div>- ) : (- <p className="text-xs text-port-text-muted">- Inspect character visual bindings, wardrobe continuity, voice profile drift, pronunciation anchors, and live hold loops.- </p>- )}- </div></div>);}diff --git a/client/src/components/fableloom/LoomProductionPanel.test.jsx b/client/src/components/fableloom/LoomProductionPanel.test.jsxindex fc8b874461..b8ffc51565 100644--- a/client/src/components/fableloom/LoomProductionPanel.test.jsx+++ b/client/src/components/fableloom/LoomProductionPanel.test.jsx@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import LoomProductionPanel from './LoomProductionPanel';import * as api from '../../services/api';@@ -29,6 +29,7 @@ describe('LoomProductionPanel', () => {],convergenceIssues: [],exactInputIssues: [],+ formatMismatches: [],};beforeEach(() => {@@ -39,21 +40,37 @@ describe('LoomProductionPanel', () => {status: 'in_progress',summary: { total: 6, completed: 2 },});- api.reviewLoomEpisodeContinuity.mockResolvedValue({- passed: false,- nodesEvaluated: 3,- summary: { errors: 1, warnings: 0, info: 0 },- findings: [- {- id: 'f-1',- category: 'visual',- severity: 'error',- code: 'MISSING_UNIVERSE_CHARACTER',- message: 'Character missing in Universe',- remediation: 'Rebind character',- nodeId: 'node-1',- },- ],+ api.updateLoom.mockResolvedValue({+ ...sampleLoom,+ renderSettings: { formatId: 'portrait-9-16' },+ });+ });++ it('defaults media to 16:9 and persists one shared image/video output format', async () => {+ const onLoomUpdate = vi.fn();+ render(+ <LoomProductionPanel+ loom={sampleLoom}+ episode={sampleEpisode}+ onSelectNode={vi.fn()}+ onLoomUpdate={onLoomUpdate}+ />,+ );++ expect(await screen.findByLabelText('Output')).toHaveValue('landscape-16-9');+ expect(screen.getByRole('option', { name: '16:9 landscape · 1024×576' })).toBeInTheDocument();++ fireEvent.change(screen.getByLabelText('Output'), { target: { value: 'portrait-9-16' } });++ await waitFor(() => {+ expect(api.updateLoom).toHaveBeenCalledWith(+ 'loom-1',+ { renderSettings: { formatId: 'portrait-9-16' } },+ { silent: true },+ );+ expect(onLoomUpdate).toHaveBeenCalledWith(expect.objectContaining({+ renderSettings: { formatId: 'portrait-9-16' },+ }));});});@@ -128,24 +145,70 @@ describe('LoomProductionPanel', () => {expect(api.startLoomEpisodeProductionBatch).not.toHaveBeenCalled();});- it('runs continuity review and displays findings with node selection', async () => {- const onSelectNode = vi.fn();- render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={onSelectNode} />);-- await waitFor(() => {- expect(screen.getByText('Run Continuity Review')).toBeInTheDocument();+ it('explains which portrait assets will be regenerated in the selected format', async () => {+ api.planLoomEpisodeProduction.mockResolvedValueOnce({+ ...samplePlan,+ formatMismatches: [{+ assetId: 'node-1:image',+ assetType: 'image',+ nodeId: 'node-1',+ nodeTitle: 'Door challenge',+ actualWidth: 576,+ actualHeight: 1024,+ expectedWidth: 1024,+ expectedHeight: 576,+ expectedAspectRatio: '16:9',+ }],});- fireEvent.click(screen.getByText('Run Continuity Review'));+ render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={vi.fn()} />);- await waitFor(() => {- expect(api.reviewLoomEpisodeContinuity).toHaveBeenCalledWith('loom-1', 'ep-1', {}, { silent: true });- expect(screen.getByText('Character missing in Universe')).toBeInTheDocument();- expect(screen.getByText('Remediation: Rebind character')).toBeInTheDocument();- });+ expect(await screen.findByText('Existing media uses another aspect ratio')).toBeInTheDocument();+ expect(screen.getByText(/1 media asset\(s\).*16:9 \(1024×576\)/i)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Door challenge · image: 576×1024 → 16:9/i })).toBeInTheDocument();+ });++ it('ignores a stale plan response after the producer changes episodes', async () => {+ let resolveFirst;+ let resolveSecond;+ api.planLoomEpisodeProduction+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))+ .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));+ const { rerender } = render(+ <LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={vi.fn()} />,+ );+ await waitFor(() => expect(api.planLoomEpisodeProduction).toHaveBeenCalledWith(+ 'loom-1', 'ep-1', { mode: 'current_canon' }, { silent: true },+ ));- const findingButton = screen.getByText('Character missing in Universe').closest('button');- fireEvent.click(findingButton);- expect(onSelectNode).toHaveBeenCalledWith('node-1');+ rerender(+ <LoomProductionPanel+ loom={sampleLoom}+ episode={{ id: 'ep-2', title: 'Episode 2' }}+ onSelectNode={vi.fn()}+ />,+ );+ await waitFor(() => expect(api.planLoomEpisodeProduction).toHaveBeenCalledWith(+ 'loom-1', 'ep-2', { mode: 'current_canon' }, { silent: true },+ ));+ await act(async () => resolveSecond({+ ...samplePlan,+ plannedAssets: [{+ id: 'asset-ep-2', nodeId: 'node-ep-2', nodeTitle: 'Episode 2 asset',+ type: 'image', status: 'ready', stageIndex: 0,+ }],+ }));+ expect(await screen.findByText('Episode 2 asset')).toBeInTheDocument();++ await act(async () => resolveFirst({+ ...samplePlan,+ plannedAssets: [{+ id: 'asset-ep-1', nodeId: 'node-ep-1', nodeTitle: 'Stale Episode 1 asset',+ type: 'image', status: 'ready', stageIndex: 0,+ }],+ }));+ expect(screen.queryByText('Stale Episode 1 asset')).not.toBeInTheDocument();+ expect(screen.getByText('Episode 2 asset')).toBeInTheDocument();});+});diff --git a/client/src/components/fableloom/LoomSeriesPlan.jsx b/client/src/components/fableloom/LoomSeriesPlan.jsxindex 9258f957ae..fbd84119c6 100644--- a/client/src/components/fableloom/LoomSeriesPlan.jsx+++ b/client/src/components/fableloom/LoomSeriesPlan.jsx@@ -5,7 +5,7 @@*/import { useCallback, useEffect, useRef, useState } from 'react';-import { Link } from 'react-router';+import { Link, useSearchParams } from 'react-router';import { BrainCircuit, CheckCircle2, ChevronDown, ChevronUp, Loader2, Plus, Save, Sparkles, Trash2 } from 'lucide-react';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import toast from '../ui/Toast';@@ -26,8 +26,10 @@ import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providerimport { fieldClass, labelClass } from './fieldStyles';import LoomAiRunStatus from './LoomAiRunStatus';import LoomEditorialAutomation from './LoomEditorialAutomation';+import { fableLoomPlotPointKind } from '../../../../server/lib/fableLoomOutline.js';const newItemId = (prefix) => `${prefix}-${uuidv4()}`;+const CHALLENGE_DESCRIPTION_TEMPLATE = 'SETUP: Establish the blockade and plant the clue. VIEWER DECISION LOOP: Offer 2–4 actionable options with escalating feedback. SUCCESS: Advance with an earned advantage. FAILURE: Continue with a visible cost. RECOVERY / PAYOFF: Converge without erasing the choice.';const normalizeDeliveryOptions = (options) => ({overnightVoicemails: options?.overnightVoicemails === true,@@ -36,7 +38,9 @@ const normalizeDeliveryOptions = (options) => ({const normalizePlan = (plan) => ({storyArc: plan?.storyArc || '',- plotPoints: Array.isArray(plan?.plotPoints) ? plan.plotPoints : [],+ plotPoints: Array.isArray(plan?.plotPoints)+ ? plan.plotPoints.map((item) => ({ ...item, kind: fableLoomPlotPointKind(item) }))+ : [],sideQuests: Array.isArray(plan?.sideQuests) ? plan.sideQuests : [],deliveryOptions: normalizeDeliveryOptions(plan?.deliveryOptions),interEpisodeVoicemails: Array.isArray(plan?.interEpisodeVoicemails)@@ -63,6 +67,8 @@ const withVoicemailDrafts = (plan, episodes) => {};export default function LoomSeriesPlan({ loom, onLoomUpdate }) {+ const [searchParams] = useSearchParams();+ const requestedSection = searchParams.get('section');const [plan, setPlan] = useState(() => normalizePlan(loom.seriesPlan));const [dirty, setDirty] = useState(false);const revisionRef = useRef(0);@@ -70,6 +76,22 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {const loomIdRef = useRef(loom.id);const routeGuard = useUnsavedChangesGuard(dirty);+ useEffect(() => {+ const targetId = {+ arc: 'fableloom-plan-arc',+ challenges: 'fableloom-plan-challenges',+ editorial: 'fableloom-plan-editorial',+ handoffs: 'fableloom-plan-handoffs',+ }[requestedSection];+ if (!targetId) return undefined;+ const frame = requestAnimationFrame(() => {+ const target = document.getElementById(targetId);+ target?.scrollIntoView?.({ behavior: 'smooth', block: 'start' });+ target?.focus?.({ preventScroll: true });+ });+ return () => cancelAnimationFrame(frame);+ }, [loom.id, requestedSection]);+useEffect(() => {if (loomIdRef.current !== loom.id) {loomIdRef.current = loom.id;@@ -162,7 +184,7 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {</p></div>- <div className="rounded-lg border border-port-border bg-port-card p-4">+ <div id="fableloom-plan-arc" tabIndex={-1} className="rounded-lg border border-port-border bg-port-card p-4 focus:outline-none"><FormFieldlabel="Story arc"hint="The beginning-to-end dramatic movement, central conflict, and intended resolution."@@ -178,22 +200,23 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {</FormField></div>- <EpisodeBeatReadiness loom={loom} />-- <LoomEditorialAutomation loom={loom} dirty={dirty} onLoomUpdate={adoptServerPlan} />-- <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)}- />+ <div id="fableloom-plan-challenges" tabIndex={-1} className="focus:outline-none">+ <PlanCollection+ title="Plot points"+ description="Order tentpoles and playable challenges, then assign each one to the episode where it must appear."+ items={plan.plotPoints}+ episodes={episodeOptions}+ onAdd={() => changePlan((current) => ({ ...current, plotPoints: [...current.plotPoints, {+ id: newItemId('plot'), kind: 'beat', title: '', description: '', episodeId: null,+ }] }))}+ onUpdate={(id, patch) => updateItem('plotPoints', id, patch)}+ onAddChallenge={() => changePlan((current) => ({ ...current, plotPoints: [...current.plotPoints, {+ id: newItemId('plot'), kind: 'challenge', title: '', description: CHALLENGE_DESCRIPTION_TEMPLATE, episodeId: null,+ }] }))}+ onRemove={(id) => removeItem('plotPoints', id)}+ onMove={(index, direction) => moveItem('plotPoints', index, direction)}+ />+ </div><PlanCollectiontitle="Side quests"@@ -209,11 +232,19 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {onMove={(index, direction) => moveItem('sideQuests', index, direction)}/>- <SeriesDeliveryPlan- plan={plan}- episodes={loom.episodes}- onChange={changePlan}- />+ <EpisodeBeatReadiness loom={loom} />++ <div id="fableloom-plan-editorial" tabIndex={-1} className="focus:outline-none">+ <LoomEditorialAutomation loom={loom} dirty={dirty} onLoomUpdate={adoptServerPlan} />+ </div>++ <div id="fableloom-plan-handoffs" tabIndex={-1} className="focus:outline-none">+ <SeriesDeliveryPlan+ plan={plan}+ episodes={loom.episodes}+ onChange={changePlan}+ />+ </div></div><aside className="w-full lg:w-[380px] xl:w-[420px] shrink-0 space-y-6 lg:sticky lg:top-0 lg:max-h-[calc(100vh-3rem)] lg:overflow-y-auto" aria-label="AI tools and actions">@@ -690,7 +721,12 @@ function SeriesDeliveryPlan({ plan, episodes, onChange }) {);}-function PlanCollection({ title, description, items, episodes, sideQuests = false, onAdd, onUpdate, onRemove, onMove }) {+function PlanCollection({+ title, description, items, episodes, sideQuests = false,+ onAdd, onAddChallenge, onUpdate, onRemove, onMove,+}) {+ const challenges = sideQuests ? [] : items.filter((item) => fableLoomPlotPointKind(item) === 'challenge');+ const assignedChallenges = challenges.filter((item) => item.episodeId);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">@@ -698,17 +734,35 @@ function PlanCollection({ title, description, items, episodes, sideQuests = fals<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 className="flex shrink-0 flex-wrap justify-end gap-1.5">+ {onAddChallenge ? (+ <button type="button" onClick={onAddChallenge} className="flex items-center gap-1 rounded border border-port-accent px-2.5 py-1.5 text-xs text-port-accent hover:bg-port-accent/10">+ <Plus size={13} /> Challenge+ </button>+ ) : null}+ <button type="button" onClick={onAdd} className="flex items-center gap-1 rounded border border-port-border px-2.5 py-1.5 text-xs hover:border-port-accent">+ <Plus size={13} /> Add+ </button>+ </div></div>+ {onAddChallenge && challenges.length ? (+ <p className={`text-xs ${assignedChallenges.length === challenges.length ? 'text-port-success' : 'text-port-warning'}`} role="status">+ {assignedChallenges.length}/{challenges.length} playable challenges mapped to episodes+ </p>+ ) : null}+{!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">+ {!sideQuests && fableLoomPlotPointKind(item) === 'challenge' ? (+ <span className="inline-flex rounded bg-port-accent/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-port-accent">+ Playable challenge+ </span>+ ) : null}<div className="flex items-center gap-2"><span className="text-xs font-medium text-port-text-muted w-6">{index + 1}.</span><inputdiff --git a/client/src/components/fableloom/LoomSeriesPlan.test.jsx b/client/src/components/fableloom/LoomSeriesPlan.test.jsxindex 7684b1e02b..7e7c0553b0 100644--- a/client/src/components/fableloom/LoomSeriesPlan.test.jsx+++ b/client/src/components/fableloom/LoomSeriesPlan.test.jsx@@ -66,6 +66,32 @@ describe('LoomSeriesPlan', () => {expect(onLoomUpdate).toHaveBeenCalledWith(updated);});+ it('adds a playable challenge as an episode-mapped plot-point contract', async () => {+ const user = userEvent.setup();+ api.updateLoom.mockResolvedValue(loom());+ renderPlan({ loom: loom(), onLoomUpdate: vi.fn() });++ await user.click(screen.getByRole('button', { name: 'Challenge' }));+ const challengeTitle = screen.getByRole('textbox', { name: 'Plot points 2 title' });+ expect(challengeTitle).toHaveValue('');+ expect(screen.getByRole('textbox', { name: 'Plot points 2 description' }).value)+ .toContain('VIEWER DECISION LOOP');+ expect(screen.getByText('0/1 playable challenges mapped to episodes')).toBeInTheDocument();+ await user.selectOptions(screen.getAllByRole('combobox', { name: 'Episode' })[1], 'ep-1');+ expect(screen.getByText('1/1 playable challenges mapped to episodes')).toBeInTheDocument();+ });++ it('presents challenge planning before outline readiness and editorial automation', () => {+ renderPlan({ loom: loom(), onLoomUpdate: vi.fn() });++ const plotPoints = screen.getByRole('heading', { name: 'Plot points' });+ const outlines = screen.getByRole('heading', { name: 'Episode beat outlines' });+ const editorial = screen.getByText('Editorial automation');++ expect(plotPoints.compareDocumentPosition(outlines) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(outlines.compareDocumentPosition(editorial) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ });+it('shows AI series analysis and recommendations for the outline', async () => {api.reviewLoomSeriesPlan.mockResolvedValue({analysis: {diff --git a/client/src/components/fableloom/LoomValidationPanel.jsx b/client/src/components/fableloom/LoomValidationPanel.jsxindex a089e3ca2f..929f941c41 100644--- a/client/src/components/fableloom/LoomValidationPanel.jsx+++ b/client/src/components/fableloom/LoomValidationPanel.jsx@@ -7,20 +7,52 @@*/import { useEffect, useMemo, useState } from 'react';-import { AlertTriangle, CircleAlert, Layers, Loader2, Sparkles, Waypoints } from 'lucide-react';+import { useSearchParams } from 'react-router';+import {+ AlertTriangle, CircleAlert, Film, Layers, ListChecks, Loader2, Sparkles, Waypoints,+} from 'lucide-react';import { useAsyncAction } from '../../hooks/useAsyncAction';-import { reviewLoomEpisode, validateLoomEpisode } from '../../services/api';+import {+ reviewLoomEpisode, reviewLoomEpisodeContinuity, validateLoomEpisode,+} from '../../services/api';+import TabPills from '../ui/TabPills';+import LoomContinuityPanel from './LoomContinuityPanel';import LoomProductionPanel from './LoomProductionPanel';+import LoomWorkflowPanel from './LoomWorkflowPanel';const severityIcon = (severity) => (severity === 'error' || severity === 'high'? <CircleAlert size={13} className="text-port-error shrink-0 mt-0.5" />: <AlertTriangle size={13} className="text-port-warning shrink-0 mt-0.5" />);-export default function LoomValidationPanel({ loom, episode, onSelectNode }) {- const [activeTab, setActiveTab] = useState('structure');- const [structural, setStructural] = useState(null);- const [review, setReview] = useState(null);+const PRODUCTION_TABS = new Set(['workflow', 'story', 'continuity', 'render']);++export default function LoomValidationPanel({+ loom,+ episode,+ onSelectNode,+ onOpenSettings,+ onOpenSeriesPlan,+ onOpenEpisodeSetup,+ onOpenPlay,+ onLoomUpdate,+}) {+ const [searchParams, setSearchParams] = useSearchParams();+ const requestedTab = searchParams.get('production');+ const activeTab = PRODUCTION_TABS.has(requestedTab) ? requestedTab : 'workflow';+ const [structuralByEpisode, setStructuralByEpisode] = useState({});+ const [reviewByEpisode, setReviewByEpisode] = useState({});+ const [continuityByEpisode, setContinuityByEpisode] = useState({});+ const structural = structuralByEpisode[episode.id] || null;+ const review = reviewByEpisode[episode.id] || null;+ const continuityReview = continuityByEpisode[episode.id] || null;++ const setActiveTab = (tab) => setSearchParams((previous) => {+ const next = new URLSearchParams(previous);+ if (tab === 'workflow') next.delete('production');+ else next.set('production', tab);+ return next;+ }, { replace: true });// Re-validate only when the graph STRUCTURE changes — a prose edit or a@@ -28,24 +60,55 @@ export default function LoomValidationPanel({ loom, episode, onSelectNode }) {// keying on updatedAt would re-run the full-loom server analysis on every// blur-save.const structureKey = useMemo(- () => [- episode.startNodeId,- ...episode.nodes.map((n) =>- `${n.id}|${n.isEnding ? 1 : 0}|${n.playbackMode || 'decision'}|${(n.transitions || []).map((t) => `${t.targetNodeId}:${t.intent}`).join(',')}`),- ].join(';'),- [episode.startNodeId, episode.nodes],+ () => (loom.episodes || []).map((item) => [+ item.id,+ item.startNodeId,+ ...(item.nodes || []).map((node) =>+ `${node.id}|${node.isEnding ? 1 : 0}|${node.playbackMode || 'decision'}|${(node.transitions || []).map((transition) => `${transition.targetNodeId}:${transition.intent}`).join(',')}`),+ ].join(';')).join('||'),+ [loom.episodes],);useEffect(() => {- validateLoomEpisode(loom.id, episode.id, { silent: true })- .then(setStructural)- .catch(() => setStructural(null));- }, [loom.id, episode.id, structureKey]);+ let active = true;+ Promise.all((loom.episodes || []).map(async (item) => [+ item.id,+ await validateLoomEpisode(loom.id, item.id, { silent: true }).catch(() => null),+ ])).then((entries) => {+ if (active) setStructuralByEpisode(Object.fromEntries(entries));+ });+ return () => { active = false; };+ }, [loom.id, loom.episodes, structureKey]);++ useEffect(() => {+ let active = true;+ Promise.all((loom.episodes || []).map(async (item) => [+ item.id,+ await reviewLoomEpisodeContinuity(loom.id, item.id, {}, { silent: true }).catch(() => null),+ ])).then((entries) => {+ if (active) setContinuityByEpisode(Object.fromEntries(entries));+ });+ return () => { active = false; };+ }, [loom.id, loom.updatedAt]);++ const handleWorkflowAction = (action) => {+ if (action === 'settings') onOpenSettings?.();+ if (action === 'series-arc') onOpenSeriesPlan?.('arc');+ if (action === 'challenges') onOpenSeriesPlan?.('challenges');+ if (action === 'editorial') onOpenSeriesPlan?.('editorial');+ if (action === 'handoffs') onOpenSeriesPlan?.('handoffs');+ if (action === 'episode-setup') onOpenEpisodeSetup?.();+ if (action === 'story-review') setActiveTab('story');+ if (action === 'continuity') setActiveTab('continuity');+ if (action === 'render') setActiveTab('render');+ if (action === 'play') onOpenPlay?.();+ };const [runReview, reviewing] = useAsyncAction(async () => {- const result = await reviewLoomEpisode(loom.id, episode.id, {}, { silent: true });- setReview(result.review);- setStructural(result.structural);+ const requestedEpisodeId = episode.id;+ const result = await reviewLoomEpisode(loom.id, requestedEpisodeId, {}, { silent: true });+ setReviewByEpisode((current) => ({ ...current, [requestedEpisodeId]: result.review }));+ setStructuralByEpisode((current) => ({ ...current, [requestedEpisodeId]: result.structural }));}, { errorMessage: 'Story review failed' });const findingRow = (item, key, nodeId) => (@@ -68,36 +131,52 @@ export default function LoomValidationPanel({ loom, episode, onSelectNode }) {return (<div className="p-3 sm:p-4 space-y-3 sm:space-y-4">- {/* Panel Tab Navigation */}- <div className="flex border-b border-port-border mb-3 text-xs overflow-x-auto scrollbar-hide touch-pan-x">- <button- type="button"- onClick={() => setActiveTab('structure')}- className={`shrink-0 whitespace-nowrap px-2.5 sm:px-3 py-2 font-medium border-b-2 flex items-center gap-1.5 ${- activeTab === 'structure'- ? 'border-port-accent text-port-accent'- : 'border-transparent text-port-text-muted hover:text-port-text'- }`}- >- <Waypoints size={13} />- Structure & Story- </button>- <button- type="button"- onClick={() => setActiveTab('production')}- className={`shrink-0 whitespace-nowrap px-2.5 sm:px-3 py-2 font-medium border-b-2 flex items-center gap-1.5 ${- activeTab === 'production'- ? 'border-port-accent text-port-accent'- : 'border-transparent text-port-text-muted hover:text-port-text'- }`}- >- <Layers size={13} />- Production & Continuity- </button>- </div>-- {activeTab === 'production' ? (- <LoomProductionPanel loom={loom} episode={episode} onSelectNode={onSelectNode} />+ <TabPills+ tabs={[+ { id: 'workflow', label: 'Workflow', icon: ListChecks },+ { id: 'story', label: 'Story', icon: Waypoints },+ { id: 'continuity', label: 'Continuity', icon: Film },+ { id: 'render', label: 'Render', icon: Layers },+ ]}+ activeTab={activeTab}+ onChange={setActiveTab}+ variant="underline"+ size="xs"+ stretch+ mobileDropdown+ mobileSelectId="fableloom-workflow-section"+ ariaLabel="Episode production sections"+ />++ {activeTab === 'workflow' ? (+ <LoomWorkflowPanel+ loom={loom}+ episode={episode}+ structural={structural}+ structuralByEpisode={structuralByEpisode}+ continuityReview={continuityReview}+ continuityByEpisode={continuityByEpisode}+ onAction={handleWorkflowAction}+ onLoomUpdate={onLoomUpdate}+ />+ ) : activeTab === 'render' ? (+ <LoomProductionPanel+ loom={loom}+ episode={episode}+ onSelectNode={onSelectNode}+ onLoomUpdate={onLoomUpdate}+ />+ ) : activeTab === 'continuity' ? (+ <LoomContinuityPanel+ loom={loom}+ episode={episode}+ review={continuityReview}+ onReviewChange={(reviewEpisodeId, result) => setContinuityByEpisode((current) => ({+ ...current,+ [reviewEpisodeId]: result,+ }))}+ onSelectNode={onSelectNode}+ />) : (<><div>diff --git a/client/src/components/fableloom/LoomValidationPanel.test.jsx b/client/src/components/fableloom/LoomValidationPanel.test.jsxnew file mode 100644index 0000000000..07f067b2ae--- /dev/null+++ b/client/src/components/fableloom/LoomValidationPanel.test.jsx@@ -0,0 +1,84 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';+import * as api from '../../services/api';+import LoomValidationPanel from './LoomValidationPanel';++vi.mock('../../services/api');+vi.mock('./LoomWorkflowPanel', () => ({+ default: () => <div>Ordered production workflow</div>,+}));+vi.mock('./LoomContinuityPanel', () => ({+ default: () => <div>Dedicated continuity workspace</div>,+}));+vi.mock('./LoomProductionPanel', () => ({+ default: ({ onLoomUpdate }) => (+ <button type="button" onClick={() => onLoomUpdate?.({ id: 'loom-updated' })}>+ Dedicated render workspace+ </button>+ ),+}));++const episode = {+ id: 'episode-1', startNodeId: 'scene-1',+ nodes: [{ id: 'scene-1', isEnding: true, transitions: [] }],+};++beforeEach(() => {+ vi.clearAllMocks();+ api.validateLoomEpisode.mockResolvedValue({+ stats: {+ errorCount: 0, automaticCutCount: 0, decisionCount: 0,+ reachableEndingCount: 1, endingCount: 1, maxDepth: 1,+ },+ issues: [],+ });+ api.reviewLoomEpisodeContinuity.mockResolvedValue({ passed: true, findings: [], summary: {} });+});++describe('LoomValidationPanel', () => {+ it('opens on the ordered workflow and separates story, continuity, and render work', async () => {+ const user = userEvent.setup();+ const onLoomUpdate = vi.fn();+ render(+ <MemoryRouter>+ <LoomValidationPanel+ loom={{ id: 'loom-1', episodes: [episode] }}+ episode={episode}+ onSelectNode={vi.fn()}+ onLoomUpdate={onLoomUpdate}+ />+ </MemoryRouter>,+ );++ expect(screen.getByText('Ordered production workflow')).toBeInTheDocument();+ await user.click(screen.getByRole('tab', { name: 'Story' }));+ await waitFor(() => expect(screen.getByText(/Graph is sound/i)).toBeInTheDocument());+ await user.click(screen.getByRole('tab', { name: 'Continuity' }));+ expect(screen.getByText('Dedicated continuity workspace')).toBeInTheDocument();+ await user.click(screen.getByRole('tab', { name: 'Render' }));+ expect(screen.getByText('Dedicated render workspace')).toBeInTheDocument();+ await user.click(screen.getByText('Dedicated render workspace'));+ expect(onLoomUpdate).toHaveBeenCalledWith({ id: 'loom-updated' });+ });++ it('restores the selected production workspace from the URL', async () => {+ render(+ <MemoryRouter initialEntries={['/?production=render']}>+ <LoomValidationPanel+ loom={{ id: 'loom-1', episodes: [episode] }}+ episode={episode}+ onSelectNode={vi.fn()}+ />+ </MemoryRouter>,+ );++ expect(screen.getByText('Dedicated render workspace')).toBeInTheDocument();+ expect(screen.getByRole('tab', { name: 'Render' })).toHaveAttribute('aria-selected', 'true');+ await waitFor(() => {+ expect(api.validateLoomEpisode).toHaveBeenCalled();+ expect(api.reviewLoomEpisodeContinuity).toHaveBeenCalled();+ });+ });+});diff --git a/client/src/components/fableloom/LoomWorkflowPanel.jsx b/client/src/components/fableloom/LoomWorkflowPanel.jsxnew file mode 100644index 0000000000..5964283719--- /dev/null+++ b/client/src/components/fableloom/LoomWorkflowPanel.jsx@@ -0,0 +1,187 @@+import { useEffect, useMemo, useState } from 'react';+import { Check, Circle, Loader2, LockKeyhole, MoveRight } from 'lucide-react';+import { fableLoomProductionWorkflow } from '../../lib/fableLoomReadiness';+import { useAsyncAction } from '../../hooks/useAsyncAction';+import { getLoomEditorialAutopilotStatus, updateLoom } from '../../services/api';++const ACTIVE_STATUSES = new Set(['running', 'canceling']);++const ACTION_LABELS = {+ settings: 'Open story settings',+ 'series-arc': 'Open the series arc',+ challenges: 'Plan playable challenges',+ editorial: 'Open editorial tools',+ handoffs: 'Author viewer handoffs',+ 'episode-setup': 'Open episode setup',+ 'story-review': 'Review structure',+ continuity: 'Open continuity review',+ render: 'Open render queue',+ play: 'Play the episode',+};++const tone = (status) => {+ if (status === 'complete') return 'border-port-success/30 bg-port-success/5 text-port-success';+ if (status === 'current') return 'border-port-accent/50 bg-port-accent/10 text-port-text';+ return 'border-port-border/70 bg-port-bg/30 text-port-text-muted';+};++export default function LoomWorkflowPanel({+ loom,+ episode,+ structural,+ structuralByEpisode,+ continuityReview,+ continuityByEpisode,+ onAction,+ onLoomUpdate,+}) {+ const [editorialRun, setEditorialRun] = useState(null);++ useEffect(() => {+ let canceled = false;+ let timer;+ setEditorialRun(null);+ const load = async () => {+ let delay = 5000;+ await getLoomEditorialAutopilotStatus(loom.id, { silent: true })+ .then(({ run }) => {+ if (canceled) return;+ setEditorialRun(run || null);+ if (ACTIVE_STATUSES.has(run?.status)) delay = 2000;+ })+ .catch(() => {});+ if (!canceled) timer = setTimeout(load, delay);+ };+ load();+ return () => {+ canceled = true;+ clearTimeout(timer);+ };+ }, [loom.id]);++ const workflow = useMemo(() => fableLoomProductionWorkflow(loom, episode, {+ structural,+ structuralByEpisode,+ editorialRun,+ continuityReview,+ continuityByEpisode,+ }), [continuityByEpisode, continuityReview, editorialRun, episode, loom, structural, structuralByEpisode]);+ const current = workflow.stages[workflow.currentIndex];+ const progress = Math.round((workflow.completedCount / workflow.totalSteps) * 100);++ const [approveEditorial, approvingEditorial] = useAsyncAction(async () => {+ const updated = await updateLoom(loom.id, {+ productionStatus: {+ ...loom.productionStatus,+ editorialApprovedAt: new Date().toISOString(),+ editorialApprovalSource: 'manual',+ deliveryApprovedAt: null,+ },+ }, { silent: true });+ onLoomUpdate?.(updated);+ }, { errorMessage: 'Could not record editorial approval' });++ const [approveDelivery, approvingDelivery] = useAsyncAction(async () => {+ const updated = await updateLoom(loom.id, {+ productionStatus: {+ ...loom.productionStatus,+ deliveryApprovedAt: new Date().toISOString(),+ },+ }, { silent: true });+ onLoomUpdate?.(updated);+ }, { errorMessage: 'Could not approve final delivery' });++ return (+ <section className="space-y-4" aria-label="Production workflow">+ <header>+ <div className="flex items-baseline justify-between gap-3">+ <div>+ <h3 className="text-sm font-semibold">Production workflow</h3>+ <p className="mt-0.5 text-xs text-port-text-muted">+ Manual authoring and AI use the same ordered gates.+ </p>+ </div>+ <span className="shrink-0 text-xs font-medium text-port-accent">+ Step {workflow.currentStep} of {workflow.totalSteps}+ </span>+ </div>+ <div+ className="mt-3 h-1.5 overflow-hidden rounded-full bg-port-border"+ role="progressbar"+ aria-label="Production progress"+ aria-valuemin="0"+ aria-valuemax="100"+ aria-valuenow={progress}+ >+ <div className="h-full rounded-full bg-port-accent transition-[width]" style={{ width: `${progress}%` }} />+ </div>+ </header>++ <ol className="space-y-1.5">+ {workflow.stages.map((stage) => (+ <li+ key={stage.id}+ className={`rounded border px-2.5 py-2 ${tone(stage.status)}`}+ aria-current={stage.status === 'current' ? 'step' : undefined}+ >+ <div className="flex items-center gap-2">+ <span className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold ${+ stage.status === 'current' ? 'bg-port-accent text-white' : 'bg-port-card'+ }`}>+ {stage.status === 'complete' ? <Check size={12} /> : stage.number}+ </span>+ <span className="min-w-0 flex-1 truncate text-xs font-medium">{stage.label}</span>+ {stage.status === 'current' && ACTIVE_STATUSES.has(editorialRun?.status) && stage.id === 'editorial'+ ? <Loader2 size={12} className="shrink-0 animate-spin text-port-accent" />+ : stage.status === 'blocked'+ ? <LockKeyhole size={11} className="shrink-0 opacity-50" />+ : <Circle size={8} className="shrink-0 fill-current" />}+ </div>+ {stage.status === 'current' ? (+ <p className="ml-7 mt-1 text-[11px] leading-relaxed text-port-text-muted">{stage.detail}</p>+ ) : null}+ </li>+ ))}+ </ol>++ {current ? (+ <div className="space-y-2">+ <button+ type="button"+ onClick={() => onAction?.(current.action)}+ className="flex min-h-11 w-full items-center justify-center gap-2 rounded bg-port-accent px-3 py-2 text-sm font-medium text-white hover:bg-port-accent/90"+ >+ {ACTION_LABELS[current.action] || 'Open current step'}+ <MoveRight size={14} />+ </button>+ {current.id === 'editorial' ? (+ <button+ type="button"+ onClick={approveEditorial}+ disabled={approvingEditorial}+ className="flex min-h-11 w-full items-center justify-center gap-2 rounded border border-port-accent px-3 py-2 text-sm font-medium text-port-accent disabled:opacity-50"+ >+ {approvingEditorial ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />}+ Mark manual editorial review complete+ </button>+ ) : null}+ {current.id === 'delivery' ? (+ <button+ type="button"+ onClick={approveDelivery}+ disabled={approvingDelivery}+ className="flex min-h-11 w-full items-center justify-center gap-2 rounded border border-port-accent px-3 py-2 text-sm font-medium text-port-accent disabled:opacity-50"+ >+ {approvingDelivery ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />}+ Approve final delivery+ </button>+ ) : null}+ </div>+ ) : (+ <p className="rounded border border-port-success/30 bg-port-success/10 p-3 text-center text-sm font-medium text-port-success">+ Production complete · 12 of 12 gates cleared+ </p>+ )}+ </section>+ );+}diff --git a/client/src/components/fableloom/LoomWorkflowPanel.test.jsx b/client/src/components/fableloom/LoomWorkflowPanel.test.jsxnew file mode 100644index 0000000000..8d33e03d69--- /dev/null+++ b/client/src/components/fableloom/LoomWorkflowPanel.test.jsx@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import * as api from '../../services/api';+import LoomWorkflowPanel from './LoomWorkflowPanel';++vi.mock('../../services/api');++const episode = {+ id: 'ep-1', number: 1, storyOutline: { validation: { status: 'valid' } },+ startNodeId: 'scene-1',+ nodes: [{ id: 'scene-1', transitions: [], isEnding: true }],+};+const loom = {+ id: 'loom-1', name: 'Example Story', premise: 'A traveler needs a guide.',+ seriesPlan: {+ storyArc: 'Suspicion becomes trust.',+ plotPoints: [{ id: 'plot-1', kind: 'challenge', title: 'The gate', description: 'A costly choice.', episodeId: 'ep-1' }],+ },+ episodes: [episode],+};++beforeEach(() => {+ vi.clearAllMocks();+ api.getLoomEditorialAutopilotStatus.mockResolvedValue({+ run: { status: 'failed', round: 1, maxRounds: 3, stepIndex: 1, stepCount: 6 },+ });+ api.updateLoom.mockResolvedValue({+ ...loom,+ productionStatus: {+ editorialApprovedAt: '2026-08-30T12:00:00.000Z',+ editorialApprovalSource: 'manual',+ deliveryApprovedAt: null,+ },+ });+});++describe('LoomWorkflowPanel', () => {+ it('shows the current production step and routes its action', async () => {+ const user = userEvent.setup();+ const onAction = vi.fn();+ render(+ <LoomWorkflowPanel+ loom={loom}+ episode={episode}+ structural={{ stats: { errorCount: 0 } }}+ continuityReview={null}+ onAction={onAction}+ />,+ );++ expect(await screen.findByText('Step 7 of 12')).toBeInTheDocument();+ expect(screen.getByText(/Latest autopilot: failed · step 1\/6/i)).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: /Open editorial tools/i }));+ expect(onAction).toHaveBeenCalledWith('editorial');+ });++ it('lets a human complete editorial review without running autopilot', async () => {+ const user = userEvent.setup();+ const onLoomUpdate = vi.fn();+ render(+ <LoomWorkflowPanel+ loom={loom}+ episode={episode}+ structural={{ stats: { errorCount: 0 } }}+ onLoomUpdate={onLoomUpdate}+ />,+ );++ await user.click(await screen.findByRole('button', { name: /Mark manual editorial review complete/i }));+ expect(api.updateLoom).toHaveBeenCalledWith('loom-1', {+ productionStatus: expect.objectContaining({+ editorialApprovedAt: expect.any(String),+ editorialApprovalSource: 'manual',+ deliveryApprovedAt: null,+ }),+ }, { silent: true });+ expect(onLoomUpdate).toHaveBeenCalledWith(expect.objectContaining({ id: 'loom-1' }));+ });+});diff --git a/client/src/components/fableloom/sceneMediaRequests.js b/client/src/components/fableloom/sceneMediaRequests.jsindex 5a8f151177..2466857f5a 100644--- a/client/src/components/fableloom/sceneMediaRequests.js+++ b/client/src/components/fableloom/sceneMediaRequests.js@@ -12,6 +12,7 @@import { composeStyledPrompt } from '../../lib/composeStyledPrompt';import { FABLELOOM_CAMERA_MOVEMENTS } from '../../../../server/lib/fableLoomCameraMovements.js';+import { asFableLoomRenderSettings } from '../../../../server/lib/fableLoomProduction.js';const withLoomStyle = (prompt, styleNotes) => {const notes = typeof styleNotes === 'string' ? styleNotes.trim() : '';@@ -21,9 +22,12 @@ const withLoomStyle = (prompt, styleNotes) => {export function buildFableLoomImageRequest({ loom, episodeId, node, stylePreset = null }) {const authoredPrompt = withLoomStyle((node?.imagePrompt || '').trim(), loom?.styleNotes);const styled = composeStyledPrompt(authoredPrompt, '', stylePreset);+ const render = asFableLoomRenderSettings(loom?.renderSettings);return {prompt: styled.prompt,...(styled.negativePrompt ? { negativePrompt: styled.negativePrompt } : {}),+ width: render.width,+ height: render.height,fableLoom: { loomId: loom.id, episodeId, nodeId: node.id },};}@@ -36,6 +40,7 @@ export function buildFableLoomVideoRequest({ loom, episodeId, node, stylePreset? `${authoredPrompt}\n\nCamera direction: ${direction}`: authoredPrompt;const styled = composeStyledPrompt(withLoomStyle(directedPrompt, loom?.styleNotes), '', stylePreset);+ const render = asFableLoomRenderSettings(loom?.renderSettings);return {prompt: styled.prompt,...(styled.negativePrompt ? { negativePrompt: styled.negativePrompt } : {}),@@ -43,6 +48,8 @@ export function buildFableLoomVideoRequest({ loom, episodeId, node, stylePresetmode: node?.image ? 'image' : 'text',...(node?.image ? { sourceImageFile: node.image } : {}),disableAudio: true,+ width: render.width,+ height: render.height,fableLoom: JSON.stringify({ loomId: loom.id, episodeId, nodeId: node.id }),};}diff --git a/client/src/components/fableloom/sceneMediaRequests.test.js b/client/src/components/fableloom/sceneMediaRequests.test.jsindex 9d149c1e80..52d42aa618 100644--- a/client/src/components/fableloom/sceneMediaRequests.test.js+++ b/client/src/components/fableloom/sceneMediaRequests.test.js@@ -13,6 +13,8 @@ describe('FableLoom scene media request composition', () => {})).toEqual({prompt: 'painted graphic novel. a scout wakes in alien grass\n\nStyle: cool rim light',negativePrompt: 'photorealism',+ width: 1024,+ height: 576,fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' },});});@@ -73,7 +75,19 @@ describe('FableLoom scene media request composition', () => {mode: 'image',sourceImageFile: 'scene.png',disableAudio: true,+ width: 1024,+ height: 576,fableLoom: JSON.stringify({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' }),});});++ it('uses one selected format for both storyboard stills and motion', () => {+ const portraitLoom = { ...loom, renderSettings: { formatId: 'portrait-9-16' } };+ const node = { id: 'node-1', imagePrompt: 'a portrait frame', videoPrompt: 'a portrait clip' };++ expect(buildFableLoomImageRequest({ loom: portraitLoom, episodeId: 'ep-1', node }))+ .toMatchObject({ width: 576, height: 1024 });+ expect(buildFableLoomVideoRequest({ loom: portraitLoom, episodeId: 'ep-1', node }))+ .toMatchObject({ width: 576, height: 1024 });+ });});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex a50a6ec013..26b891da3c 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -48,7 +48,7 @@ grep -i "what you want to do" client/src/lib/README.md| `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. || `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. `federatedMediaModelsForPeer(peer, kind)` intersects the local per-kind allowlist with the peer’s advertised capabilities and returns the capability entries (with their `ready` / `unavailableReason`), so no surface can offer a model the server would refuse or hide why a listed one cannot run. `federatedMediaSupports(status, feature, capability)` mirrors the server helper of the same name and is the ONE place the "absent reads as false" rule lives on this side (#4826): it answers whether the peer’s BUILD speaks a wire feature (`lyrics`, `inputAssets`) from the status-root `features` list, retaining only the legacy `inputAssets` capability block for peers on the previous build because that signal is genuinely per-model, and `peerMediaProviderSnapshot(peer)` returns the status payload to ask it against. `peerModelAcceptsInput(capability, role, status)` / `peerModelRequiresInput(capability)` read the capability’s `inputAssets` block — which conditioning slots (`initImage` / `referenceImages` / `sourceImage` / `lastImage`) a peer model takes, and whether it can render without one — gated first on the build speaking conditioning at all, with **absent reading as NO**, so a provider predating that field is never offered a render it would reject. Display only — the server re-probes and fail-closes before any job leaves. |-| `fableLoomReadiness.js` | Ordered FableLoom story-first readiness: every episode outline validated, configured voicemail/teaser handoffs authored, then media generation is enabled. |+| `fableLoomReadiness.js` | Ordered FableLoom readiness plus the twelve-stage producer workflow spanning foundation, challenges, outlines, editorial, continuity, media, and final hosting. || `glbFailure.js` | Turns a 3D asset failure into an actionable sentence. `glbFailureHint(error)` matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns `null` when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. `glbErrorText(error)` reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by `media/GlbViewer.jsx` and `cos/CoSCanvasGuard.jsx`. || `grokVideoClip.js` | Mirror of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. || `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |diff --git a/client/src/lib/fableLoomReadiness.js b/client/src/lib/fableLoomReadiness.jsindex 56aba56371..5ba63f67e0 100644--- a/client/src/lib/fableLoomReadiness.js+++ b/client/src/lib/fableLoomReadiness.js@@ -33,6 +33,35 @@ const reachableNodes = (episode) => {return ordered;};+const playableChallenge = (item) => item?.kind === 'challenge'+ || (item?.kind == null && /^challenge\s*(?:[-—:]|$)/i.test(item?.title?.trim() || ''));++const nodeHasMotionDelivery = (node) => {+ const assets = node?.playbackAssets || {};+ const hasEntry = hasText(node?.videoHistoryId) || hasText(assets.entryVideoHistoryId);+ if (!hasEntry) return false;+ if (node?.playbackMode !== 'decision' || node?.isEnding) return true;+ const exits = assets.exitByTransition || {};+ return asArray(assets.holdLoopVideoHistoryIds).length > 0+ && asArray(node.transitions).every((transition) => hasText(exits[transition.id]));+};++const deliveryHandoffsReady = (loom) => {+ const episodes = asArray(loom?.episodes);+ const plan = loom?.seriesPlan || {};+ const options = plan.deliveryOptions || {};+ if (options.overnightVoicemails === true) {+ const messages = new Map(asArray(plan.interEpisodeVoicemails).map((item) => (+ [`${item?.fromEpisodeId}::${item?.toEpisodeId}`, item]+ )));+ const missing = episodes.slice(0, -1).some((episode, index) => (+ !hasText(messages.get(`${episode.id}::${episodes[index + 1]?.id}`)?.transcript)+ ));+ if (missing) return false;+ }+ return options.nextSeasonTeaser !== true || hasText(plan.nextSeasonTeaser?.transcript);+};+export function fableLoomEpisodeOrderReadiness(loom, episode) {const episodes = asArray(loom?.episodes);const currentIndex = episodes.findIndex((candidate) => candidate?.id === episode?.id);@@ -104,3 +133,134 @@ export function fableLoomMediaReadiness(loom, episode) {if (!story.ready) return story;return fableLoomEpisodeOrderReadiness(loom, episode);}++/**+ * One producer-facing sequence shared by manual and AI-assisted work. The+ * first incomplete stage is the current action; later incomplete stages stay+ * visibly blocked while already-finished downstream work remains acknowledged.+ */+export function fableLoomProductionWorkflow(loom, episode, {+ structural = null,+ structuralByEpisode = null,+ editorialRun = null,+ continuityReview = null,+ continuityByEpisode = null,+} = {}) {+ const episodes = asArray(loom?.episodes);+ const plotPoints = asArray(loom?.seriesPlan?.plotPoints);+ const challenges = plotPoints.filter(playableChallenge);+ const reachable = episodes.flatMap(reachableNodes);+ const outlinesReady = episodes.length > 0+ && episodes.every((item) => item?.storyOutline?.validation?.status === 'valid');+ const teleplaysReady = episodes.length > 0 && episodes.every((item) => asArray(item?.nodes).length > 0);+ const structuralResults = episodes.map((item) => (+ structuralByEpisode?.[item.id] || (item.id === episode?.id ? structural : null)+ ));+ const structureReviewedCount = structuralResults.filter(Boolean).length;+ const structurePassedCount = structuralResults.filter((result) => result?.stats?.errorCount === 0).length;+ const structureReady = teleplaysReady && episodes.length > 0+ && structurePassedCount === episodes.length;+ const planReady = challenges.length > 0 && plotPoints.every((item) => (+ hasText(item?.title) && hasText(item?.description) && hasText(item?.episodeId)+ ));+ const imagesReady = reachable.length > 0 && reachable.every((node) => hasText(node?.image));+ const motionReady = reachable.length > 0 && reachable.every(nodeHasMotionDelivery)+ && structural?.productionReadiness?.ready !== false;+ const handoffsReady = deliveryHandoffsReady(loom);+ const continuityResults = episodes.map((item) => (+ continuityByEpisode?.[item.id] || (item.id === episode?.id ? continuityReview : null)+ ));+ const continuityReviewedCount = continuityResults.filter(Boolean).length;+ const continuityPassedCount = continuityResults.filter((result) => result?.passed === true).length;+ const continuityReady = episodes.length > 0 && continuityPassedCount === episodes.length;+ const editorialIsCurrent = hasText(loom?.productionStatus?.editorialApprovedAt)+ || editorialRun?.status === 'completed';+ const deliveryApproved = hasText(loom?.productionStatus?.deliveryApprovedAt);++ const stages = [+ {+ id: 'foundation', label: 'Story foundation', action: 'settings',+ complete: hasText(loom?.name) && (hasText(loom?.premise) || hasText(loom?.logline)),+ detail: 'Lock the format, premise, protagonist, and audience participation mode.',+ },+ {+ id: 'series-arc', label: 'Series arc', action: 'series-arc',+ complete: hasText(loom?.seriesPlan?.storyArc),+ detail: 'Define the beginning-to-end dramatic movement before expanding episodes.',+ },+ {+ id: 'challenges', label: 'Plot points & playable challenges', action: 'challenges',+ complete: planReady,+ detail: challenges.length+ ? `${challenges.length} playable challenge${challenges.length === 1 ? '' : 's'} mapped to episodes; every plot point needs an assignment.`+ : 'Add at least one playable challenge, then map every tentpole and challenge to an episode; each challenge needs setup, a choice loop, success, failure, and recovery.',+ },+ {+ id: 'outlines', label: 'Episode beat outlines', action: 'episode-setup',+ complete: outlinesReady,+ detail: `${episodes.filter((item) => item?.storyOutline?.validation?.status === 'valid').length}/${episodes.length} episode outlines validated.`,+ },+ {+ id: 'teleplays', label: 'Expand teleplay scenes', action: 'episode-setup',+ complete: teleplaysReady,+ detail: `${episodes.filter((item) => asArray(item?.nodes).length > 0).length}/${episodes.length} episodes expanded into scene graphs.`,+ },+ {+ id: 'structure', label: 'Structure & path checks', action: 'story-review',+ complete: structureReady,+ detail: structureReviewedCount+ ? `${structurePassedCount}/${episodes.length} episode graphs pass every path and reachable-ending check.`+ : 'Validate every episode graph, choice, and reachable ending.',+ },+ {+ id: 'editorial', label: 'Editorial review', action: 'editorial',+ complete: editorialIsCurrent,+ detail: editorialRun?.status+ ? `Latest autopilot: ${editorialRun.status}${editorialRun.stepIndex ? ` · step ${editorialRun.stepIndex}/${editorialRun.stepCount}` : ''}.`+ : 'Review manually or let autopilot repair the series and exercise every path until the gates pass.',+ },+ {+ id: 'continuity', label: 'Continuity & canon', action: 'continuity',+ complete: continuityReady,+ detail: continuityReviewedCount+ ? `${continuityPassedCount}/${episodes.length} episodes pass character, wardrobe, voice, playback, and convergence continuity.`+ : 'Check every episode for character, wardrobe, voice, pronunciation, playback, and convergence continuity.',+ },+ {+ id: 'handoffs', label: 'Viewer handoffs', action: 'handoffs',+ complete: handoffsReady,+ detail: handoffsReady+ ? 'Every enabled between-episode voicemail and finale teaser is authored.'+ : 'Author each enabled overnight voicemail and the finale teaser.',+ },+ {+ id: 'storyboards', label: 'Storyboard images', action: 'render',+ complete: imagesReady,+ detail: `${reachable.filter((node) => hasText(node?.image)).length}/${reachable.length} reachable scenes have storyboard images.`,+ },+ {+ id: 'motion', label: 'Motion & live voice assets', action: 'render',+ complete: motionReady,+ detail: `${reachable.filter(nodeHasMotionDelivery).length}/${reachable.length} reachable scenes have their required entry, hold, and exit motion assets.`,+ },+ {+ id: 'delivery', label: 'Final playthrough & host', action: 'play',+ complete: deliveryApproved,+ detail: deliveryApproved+ ? 'The end-to-end audience experience is approved for the hosted demo.'+ : 'Run the audience experience end to end, then approve the final route for the hosted demo.',+ },+ ];+ const currentIndex = stages.findIndex((stage) => !stage.complete);+ return {+ currentIndex,+ currentStep: currentIndex < 0 ? stages.length : currentIndex + 1,+ totalSteps: stages.length,+ completedCount: currentIndex < 0 ? stages.length : currentIndex,+ stages: stages.map((stage, index) => ({+ ...stage,+ number: index + 1,+ status: stage.complete ? 'complete' : index === currentIndex ? 'current' : 'blocked',+ })),+ };+}diff --git a/client/src/lib/fableLoomReadiness.test.js b/client/src/lib/fableLoomReadiness.test.jsindex 595ade008b..b11fd41910 100644--- a/client/src/lib/fableLoomReadiness.test.js+++ b/client/src/lib/fableLoomReadiness.test.js@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {- fableLoomEpisodeOrderReadiness, fableLoomMediaReadiness, fableLoomStoryReadiness,+ fableLoomEpisodeOrderReadiness, fableLoomMediaReadiness,+ fableLoomProductionWorkflow, fableLoomStoryReadiness,} from './fableLoomReadiness.js';const outline = { validation: { status: 'valid' } };@@ -62,4 +63,146 @@ describe('FableLoom story-first readiness', () => {});expect(fableLoomMediaReadiness(loom, loom.episodes[1]).ready).toBe(false);});++ it('orders manual and AI work into one twelve-stage production sequence', () => {+ const loom = {+ name: 'Example Story', premise: 'A courier follows a dangerous signal.',+ seriesPlan: {+ storyArc: 'Suspicion becomes trust.',+ plotPoints: [{+ id: 'plot-1', title: 'Challenge — Locked gate', description: 'Setup and costly outcomes.', episodeId: 'ep-1',+ }],+ },+ episodes: [{ id: 'ep-1', number: 1, storyOutline: outline, nodes: [] }],+ };++ const workflow = fableLoomProductionWorkflow(loom, loom.episodes[0]);++ expect(workflow).toMatchObject({ currentStep: 5, totalSteps: 12, completedCount: 4 });+ expect(workflow.stages[2]).toMatchObject({+ id: 'challenges', status: 'complete', detail: expect.stringContaining('1 playable challenge'),+ });+ expect(workflow.stages[4]).toMatchObject({ id: 'teleplays', status: 'current' });+ expect(workflow.stages[5]).toMatchObject({ id: 'structure', status: 'blocked' });+ });++ it('keeps challenge planning current until the story names a playable challenge', () => {+ const episode = { id: 'ep-1', number: 1, storyOutline: outline, nodes: [] };+ const workflow = fableLoomProductionWorkflow({+ name: 'Example Story', premise: 'A courier follows a dangerous signal.',+ seriesPlan: {+ storyArc: 'Suspicion becomes trust.',+ plotPoints: [{ id: 'plot-1', title: 'Arrival', description: 'The courier lands.', episodeId: 'ep-1' }],+ },+ episodes: [episode],+ }, episode);++ expect(workflow.currentStep).toBe(3);+ expect(workflow.stages[2]).toMatchObject({+ id: 'challenges', status: 'current', detail: expect.stringContaining('Add at least one playable challenge'),+ });+ });++ it('advances through review and media stages from saved production evidence', () => {+ const motion = {+ entryVideoHistoryId: 'video-entry',+ holdLoopVideoHistoryIds: ['video-hold'],+ exitByTransition: { 'path-1': 'video-exit' },+ };+ const episode = {+ id: 'ep-1', number: 1, startNodeId: 'scene-1', storyOutline: outline,+ nodes: [{+ id: 'scene-1', image: 'scene.png', playbackMode: 'decision', isEnding: false,+ transitions: [{ id: 'path-1', targetNodeId: 'ending' }], playbackAssets: motion,+ }, {+ id: 'ending', image: 'ending.png', videoHistoryId: 'video-ending', isEnding: true, transitions: [],+ }],+ };+ const loom = {+ name: 'Example Story', logline: 'A choice opens the way.',+ seriesPlan: {+ storyArc: 'The way opens.',+ plotPoints: [{ id: 'plot-1', title: 'Challenge — The gate', description: 'A costly choice.', episodeId: 'ep-1' }],+ },+ episodes: [episode],+ };++ const workflow = fableLoomProductionWorkflow(loom, episode, {+ structural: { stats: { errorCount: 0 }, productionReadiness: { ready: true } },+ editorialRun: { status: 'completed' },+ continuityReview: { passed: true, summary: { errors: 0, warnings: 0 } },+ });++ expect(workflow.currentStep).toBe(12);+ expect(workflow.stages.slice(0, 11).every((stage) => stage.status === 'complete')).toBe(true);+ expect(workflow.stages[11]).toMatchObject({ id: 'delivery', status: 'current' });+ });++ it('requires series-wide structure and continuity evidence, not only the selected episode', () => {+ const episodes = [+ { id: 'ep-1', number: 1, storyOutline: outline, nodes: [{ id: 'one', isEnding: true, transitions: [] }] },+ { id: 'ep-2', number: 2, storyOutline: outline, nodes: [{ id: 'two', isEnding: true, transitions: [] }] },+ ];+ const base = {+ name: 'Example Story', premise: 'Two routes must both hold.',+ seriesPlan: {+ storyArc: 'Both episodes resolve one pursuit.',+ plotPoints: [{+ id: 'challenge-1', kind: 'challenge', title: 'Cross the gate',+ description: 'A setup, decision, outcome, and recovery.', episodeId: 'ep-1',+ }],+ },+ episodes,+ };+ const workflow = fableLoomProductionWorkflow(base, episodes[0], {+ structuralByEpisode: {+ 'ep-1': { stats: { errorCount: 0 } },+ 'ep-2': { stats: { errorCount: 1 } },+ },+ continuityByEpisode: {+ 'ep-1': { passed: true },+ 'ep-2': { passed: false },+ },+ });++ expect(workflow.stages[5]).toMatchObject({+ id: 'structure', status: 'current', detail: expect.stringContaining('1/2 episode graphs pass'),+ });+ expect(workflow.stages[7]).toMatchObject({+ id: 'continuity', detail: expect.stringContaining('1/2 episodes pass'),+ });+ });++ it('reaches twelve of twelve after durable final-delivery approval', () => {+ const episode = {+ id: 'ep-1', number: 1, storyOutline: outline, startNodeId: 'ending',+ nodes: [{+ id: 'ending', image: 'ending.png', videoHistoryId: 'ending-video',+ isEnding: true, transitions: [],+ }],+ };+ const loom = {+ name: 'Example Story', premise: 'A route reaches its ending.',+ seriesPlan: {+ storyArc: 'The route resolves.',+ plotPoints: [{+ id: 'challenge-1', kind: 'challenge', title: 'Cross the gate',+ description: 'A complete playable challenge.', episodeId: 'ep-1',+ }],+ },+ productionStatus: {+ editorialApprovedAt: '2026-08-30T12:00:00.000Z',+ editorialApprovalSource: 'manual',+ deliveryApprovedAt: '2026-08-30T13:00:00.000Z',+ },+ episodes: [episode],+ };+ const workflow = fableLoomProductionWorkflow(loom, episode, {+ structuralByEpisode: { 'ep-1': { stats: { errorCount: 0 }, productionReadiness: { ready: true } } },+ continuityByEpisode: { 'ep-1': { passed: true } },+ });++ expect(workflow).toMatchObject({ currentIndex: -1, currentStep: 12, completedCount: 12 });+ expect(workflow.stages.every((stage) => stage.status === 'complete')).toBe(true);+ });});diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsxindex 4e6e28cbde..4aeddb5633 100644--- a/client/src/pages/FableLoomStory.jsx+++ b/client/src/pages/FableLoomStory.jsx@@ -697,6 +697,13 @@ export default function FableLoomStory({ view = 'graph' }) {loom={loom}episode={episode}onSelectNode={selectNode}+ onOpenSettings={() => setSettingsOpen(true)}+ onOpenSeriesPlan={(section) => navigate(+ `${episodePath('plan')}${section ? `?section=${encodeURIComponent(section)}` : ''}`,+ )}+ onOpenEpisodeSetup={() => setSetupOpen(true)}+ onOpenPlay={() => setPlayOpen(true)}+ onLoomUpdate={setLoom}/>)}</div>@@ -706,6 +713,7 @@ export default function FableLoomStory({ view = 'graph' }) {{episode && (<EpisodeSetupDrawer+ key={episode.id}open={setupOpen}onClose={() => setSetupOpen(false)}loom={loom}@@ -769,9 +777,11 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed// Sync from the record on episode switch ONLY — re-syncing on every server// echo would clobber typing in a sibling field while a blur-save- // round-trips (same rule as the scene editor).+ // round-trips (same rule as the scene editor). Guidance is intentionally+ // episode-local scratch input; carrying it into the next episode can make an+ // otherwise valid outline request contradict that episode's graph.useEffect(() => {- setForm((prev) => ({ ...prev, title: episode.title || '', synopsis: episode.synopsis || '' }));+ setForm({ title: episode.title || '', synopsis: episode.synopsis || '', guidance: '' });}, [episode.id]);const saveMeta = async (key) => {diff --git a/client/src/pages/FableLoomStory.test.jsx b/client/src/pages/FableLoomStory.test.jsxindex 13ab1355d5..e609984571 100644--- a/client/src/pages/FableLoomStory.test.jsx+++ b/client/src/pages/FableLoomStory.test.jsx@@ -233,6 +233,28 @@ describe('FableLoomStory episode expansion safety', () => {expect(screen.getByLabelText('Synopsis (feeds the weave)')).toHaveValue('A choice waits in the dark.');});+ it('clears outline guidance when the editor switches episodes', async () => {+ const user = userEvent.setup();+ api.getLoom.mockResolvedValue(loom({+ episodes: [+ episode(),+ episode({ id: 'ep-2', number: 2, title: 'The Second Door', synopsis: 'A different blockade.' }),+ ],+ }));+ renderEditor('/fableloom/loom-1/ep-1');++ await user.click(await screen.findByRole('button', { name: 'Edit episode' }));+ const guidance = screen.getByLabelText('Guidance (optional)');+ await user.type(guidance, 'Use the first episode lock code.');++ await user.click(screen.getByRole('button', { name: 'Close settings' }));+ await user.click(screen.getByRole('tab', { name: '2. The Second Door' }));+ await user.click(screen.getByRole('button', { name: 'Edit episode' }));++ expect(screen.getByLabelText('Title')).toHaveValue('The Second Door');+ expect(screen.getByLabelText('Guidance (optional)')).toHaveValue('');+ });+it('confirms before replacing an existing episode scene graph', async () => {const user = userEvent.setup();const existingEpisode = episode({ nodes: [@@ -363,6 +385,8 @@ describe('FableLoomStory scene media lifecycle', () => {expect(api.generateImage).toHaveBeenCalledWith({prompt: 'painted ink. an ancient gate in alien grass\n\nStyle: blue dusk lighting',negativePrompt: 'photorealism',+ width: 1024,+ height: 576,fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' },}, { silent: true });expect(screen.getByTestId('canvas-image-status')).toHaveTextContent('queued');@@ -430,6 +454,8 @@ describe('FableLoomStory scene media lifecycle', () => {await waitFor(() => expect(api.generateImage).toHaveBeenCalledWith({prompt: 'the same scout crosses into the observatory',+ width: 1024,+ height: 576,fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-2' },}, { silent: true }));});@@ -462,6 +488,8 @@ describe('FableLoomStory scene media lifecycle', () => {await waitFor(() => expect(api.generateImage).toHaveBeenCalledTimes(1));expect(api.generateImage.mock.calls[0]).toEqual([{prompt: 'the scout enters the observatory',+ width: 1024,+ height: 576,fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-2' },}, { silent: true }]);expect(toastMocks.error).toHaveBeenCalledWith(diff --git a/data.reference/prompts/stages/fableloom-generate-series-plan.md b/data.reference/prompts/stages/fableloom-generate-series-plan.mdindex 8c941bedad..a10c725dc5 100644--- a/data.reference/prompts/stages/fableloom-generate-series-plan.md+++ b/data.reference/prompts/stages/fableloom-generate-series-plan.md@@ -17,7 +17,8 @@ You are the series architect for an interactive branching story. Draft the compl## Planning contract- Write a clear beginning-to-end `storyArc`: protagonist pressure, escalation, irreversible midpoint, climax, resolution, and thematic movement. Account for meaningful local branches while keeping the series-level promises and payoffs legible.-- Draft 6–12 ordered `plotPoints`. Each is a tentpole beat with a concise title and a description of what happens, why it matters, and what changes.+- Draft 6–12 ordered `plotPoints`. Give each a durable `kind`: `"beat"` for a fixed tentpole or `"challenge"` for a blockade the viewer helps solve. Include several concrete playable challenges when the premise supports them. Each item needs a concise title and a description of what happens, why it matters, and what changes.+- A `kind: "challenge"` description must name the planted clue or capability, the viewer decision loop, distinct success and failure consequences, and the recovery/payoff that lets failure continue with a visible cost.- Draft 2–5 `sideQuests`. Each supporting thread needs a purpose, escalation, and payoff that strengthens the main arc rather than distracting from it.- Episode references must use an exact episode id from the supplied outline. Use `null` when no fitting episode exists yet; never invent an episode id.- Side-quest status is one of `idea`, `planned`, `active`, or `resolved`. A new scaffold normally uses `planned`.@@ -29,7 +30,7 @@ Return ONLY valid JSON matching this shape:{"storyArc": "complete dramatic arc","plotPoints": [- { "title": "tentpole beat", "description": "what happens, why it matters, and what changes", "episodeId": "episode id or null" }+ { "kind": "beat or challenge", "title": "tentpole beat", "description": "what happens, why it matters, and what changes", "episodeId": "episode id or null" }],"sideQuests": [{ "title": "supporting thread", "description": "purpose, escalation, and payoff", "status": "planned", "startEpisodeId": "episode id or null", "endEpisodeId": "episode id or null" }diff --git a/data.reference/prompts/stages/fableloom-outline-episode.md b/data.reference/prompts/stages/fableloom-outline-episode.mdindex 19b0d5413c..9c153bc4f6 100644--- a/data.reference/prompts/stages/fableloom-outline-episode.md+++ b/data.reference/prompts/stages/fableloom-outline-episode.md@@ -39,6 +39,7 @@ You are the story architect for one episode of an interactive branching series.- Mark `protagonistPresence: "offscreen"` for decision beats where the protagonist speaks directly to the audience through the communicator. Those beats are the side-device conversation: keep the visual beat open-ended and do not put the protagonist in the storyboard. Use `"onscreen"` when the protagonist is visibly present; choose deliberately for every beat.- Every beat must be reachable from `startKey`. Every non-ending beat needs a path forward. Endings have no outgoing paths, and their outcomes must differ in consequence or tone rather than only in label.- Continue the exact protagonist, character identities, locations, objects, unresolved threads, and emotional consequences established by the preceding episodes. Do not replace the established protagonist with a new one merely to create novelty.+- The Story section names every assigned plot point with its exact id and kind. Copy the exact id into `plotPointId` on beats that realize it. For every `kind=challenge`, map separate beats for all five `challengePhase` values: `setup`, `decision`, `success`, `failure`, and `recovery`. Setup must lead to the decision loop; the decision must reach both success and failure; both outcomes must continue to recovery/payoff. Do not reset or dead-end failure.- The final beat of an episode should make the next episode feel necessary. Series delivery notes may require an overnight voicemail between episodes or a next-season teaser after the final ending; preserve those promises in the beat plan without writing the voicemail itself here.Return ONLY valid JSON matching this shape — no prose, markdown fence, or commentary:@@ -51,6 +52,8 @@ Return ONLY valid JSON matching this shape — no prose, markdown fence, or comm"key": "s1","title": "short evocative beat title","summary": "one to three sentence log-line",+ "plotPointId": "exact assigned plot-point id or null",+ "challengePhase": "setup, decision, success, failure, recovery, or null","playbackMode": "cut","audienceConnection": "disconnected","protagonistPresence": "onscreen",diff --git a/data.reference/prompts/stages/fableloom-weave-episode.md b/data.reference/prompts/stages/fableloom-weave-episode.mdindex e8909e1c41..d2dc6e25c7 100644--- a/data.reference/prompts/stages/fableloom-weave-episode.md+++ b/data.reference/prompts/stages/fableloom-weave-episode.md@@ -28,7 +28,7 @@ When an existing graph is present, this is a reweave: preserve its story events,{{outlineDigest}}-When a validated beat outline is present, it is the authoritative story plan for this expansion. Reuse every supplied outline beat `key` exactly, including `startKey` and transition `targetKey` values; return one node for every beat with no additions or omissions. Preserve each beat's title, playback mode, audience connection, protagonist presence, ending contract, path targets, and path intents exactly. Add only the scene-level prose and production directions needed to make those beats playable. Do not replace the established protagonist, world, or episode handoff.+When a validated beat outline is present, it is the authoritative story plan for this expansion. Reuse every supplied outline beat `key` exactly, including `startKey` and transition `targetKey` values; return one node for every beat with no additions or omissions. Preserve each beat's title, `plotPointId`, `challengePhase`, playback mode, audience connection, protagonist presence, ending contract, path targets, and path intents exactly. Add only the scene-level prose and production directions needed to make those beats playable. Do not replace the established protagonist, world, or episode handoff.## Design contract@@ -66,6 +66,8 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"key": "s1","title": "string","prose": "string",+ "plotPointId": "exact assigned plot-point id or null",+ "challengePhase": "setup, decision, success, failure, recovery, or null","imagePrompt": "string","videoPrompt": "string","cameraMovement": "slow-dolly-in",diff --git a/scripts/migrations/288-fableloom-scene-format.js b/scripts/migrations/288-fableloom-scene-format.jsindex da2cb1c25d..fa44f56fc2 100644--- a/scripts/migrations/288-fableloom-scene-format.js+++ b/scripts/migrations/288-fableloom-scene-format.js@@ -32,7 +32,7 @@ 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': 'b4d363db94fd8a9928fa977745c76ff9', // post-321 outline expansion contract+ 'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e', // post-324 challenge mapping'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 deb6da4a32..17d9b1ad96 100644--- a/scripts/migrations/310-fableloom-camera-cuts.js+++ b/scripts/migrations/310-fableloom-camera-cuts.js@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'fableloom-weave-episode.md': 'b4d363db94fd8a9928fa977745c76ff9', // post-321 outline expansion contract+ 'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e', // post-324 challenge mapping'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da','fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670',};diff --git a/scripts/migrations/311-fableloom-audience-participation.js b/scripts/migrations/311-fableloom-audience-participation.jsindex f1f83315c8..ea7fd47fdd 100644--- a/scripts/migrations/311-fableloom-audience-participation.js+++ b/scripts/migrations/311-fableloom-audience-participation.js@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'fableloom-weave-episode.md': 'b4d363db94fd8a9928fa977745c76ff9', // post-321 outline expansion contract+ 'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e', // post-324 challenge mapping'fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da','fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670','fableloom-review.md': 'c26a641f6d0530caef7d1186c3b09937',diff --git a/scripts/migrations/319-fableloom-protagonist-continuity.js b/scripts/migrations/319-fableloom-protagonist-continuity.jsindex dd483aebd0..d1d9c7bb26 100644--- a/scripts/migrations/319-fableloom-protagonist-continuity.js+++ b/scripts/migrations/319-fableloom-protagonist-continuity.js@@ -12,8 +12,8 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'fableloom-weave-episode.md': 'b4d363db94fd8a9928fa977745c76ff9',- 'fableloom-outline-episode.md': '513b2b5b8fa98766852cdde7b87198c9',+ 'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e',+ 'fableloom-outline-episode.md': '820b8c157c1977b34eb317e44236519e','fableloom-review-episode-outline.md': '8154b4c289b10268df8fd3c625bcdac2',};diff --git a/scripts/migrations/321-fableloom-outline-expansion-contract.js b/scripts/migrations/321-fableloom-outline-expansion-contract.jsindex 737d9a0a27..d7f84f79a4 100644--- a/scripts/migrations/321-fableloom-outline-expansion-contract.js+++ b/scripts/migrations/321-fableloom-outline-expansion-contract.js@@ -7,7 +7,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'fableloom-weave-episode.md': 'b4d363db94fd8a9928fa977745c76ff9',+ 'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/323-fableloom-render-format.js b/scripts/migrations/323-fableloom-render-format.jsnew file mode 100644index 0000000000..d44788a40b--- /dev/null+++ b/scripts/migrations/323-fableloom-render-format.js@@ -0,0 +1,14 @@+/**+ * Register the additive FableLoom render-format pin.+ *+ * Existing records need no eager rewrite: sanitizeLoom backfills the explicit+ * 16:9 landscape default on read, and the next ordinary write persists it.+ * The federation schema gate advances separately so an older peer cannot+ * round-trip a chosen format away.+ */++export default {+ async up() {+ console.log('🧶 FableLoom render format: existing stories default to explicit 16:9 landscape on read');+ },+};diff --git a/scripts/migrations/324-fableloom-playable-challenge-contract.js b/scripts/migrations/324-fableloom-playable-challenge-contract.jsnew file mode 100644index 0000000000..74d1b075ad--- /dev/null+++ b/scripts/migrations/324-fableloom-playable-challenge-contract.js@@ -0,0 +1,27 @@+/** Upgrade FableLoom prompts with durable challenge-to-scene mapping. */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'fableloom-generate-series-plan.md': ['2591cf4ca6cc160765f029fcc497dc35'],+ 'fableloom-outline-episode.md': ['513b2b5b8fa98766852cdde7b87198c9'],+ 'fableloom-weave-episode.md': ['b4d363db94fd8a9928fa977745c76ff9'],+};++export const NEW_SHIPPED_MD5 = {+ 'fableloom-generate-series-plan.md': '27336d8c64e6193aecd1ba697f52315e',+ 'fableloom-outline-episode.md': '820b8c157c1977b34eb317e44236519e',+ 'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'FableLoom playable challenge phase mapping',+ customizedHint: (filename) =>+ ` Merge the durable plot-point kind and challenge-phase rules from\n`+ + ` data.reference/prompts/stages/${filename} into the installed template.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/324-fableloom-playable-challenge-contract.test.js b/scripts/migrations/324-fableloom-playable-challenge-contract.test.jsnew file mode 100644index 0000000000..551efdd355--- /dev/null+++ b/scripts/migrations/324-fableloom-playable-challenge-contract.test.js@@ -0,0 +1,16 @@+import { describe } from 'vitest';++import migration, {+ applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5,+} from './324-fableloom-playable-challenge-contract.js';+import { runPromptMigrationTests } from './_testHelpers.js';++describe('migration 324 — FableLoom playable challenge prompts', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-324-',+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 8f93f81245..e4f4581982 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -55,13 +55,14 @@ 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', '4c9454d1537c4ebb3becbfa04fae3ed8', '18a442e39b973e4074a0d595928a665d', 'e0f8d864caa8746912b56cd567f1c09d'],+ 'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46', '1b27f5b0073a304c21079aa6e2c71447', '4c9454d1537c4ebb3becbfa04fae3ed8', '18a442e39b973e4074a0d595928a665d', 'e0f8d864caa8746912b56cd567f1c09d', 'b4d363db94fd8a9928fa977745c76ff9'],'fableloom-branch-node.md': ['f558e4804b056a5961af1ea74fdef2ba', '6279b1c9912c300363a727245d22fe84', 'c14e2b9c435e43a8c3b134a62cd66d08'],'fableloom-play-turn.md': ['bb33dc9bc483668d88196ca972d5f364'],'fableloom-feedback-episode.md': ['43d1525fcedce99b933ae5b003516a36', 'd09bb405478d24c294b0c658ef365cd1'],'fableloom-review.md': ['2802f269f246e00ec5a8937637d42de6'],- 'fableloom-outline-episode.md': ['3f5144103b2ab6203fa071ff5026251b'],+ 'fableloom-outline-episode.md': ['3f5144103b2ab6203fa071ff5026251b', '513b2b5b8fa98766852cdde7b87198c9'],'fableloom-review-episode-outline.md': ['96d631104155ff11be08bcc5144cca1c'],+ 'fableloom-generate-series-plan.md': ['2591cf4ca6cc160765f029fcc497dc35'],};const EXPECTED_STAGE_NEW = {'pipeline-idea-expansion.md': 'a032e4a724251ed3e3495d33c4dbab8e',@@ -95,13 +96,14 @@ const EXPECTED_STAGE_NEW = {'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410','pipeline-observer.md': '29e0212d2252b1be3278f20e2959eb8e','pipeline-self-improve.md': '95b378832ff78e5976a6a63fcf328090',- 'fableloom-weave-episode.md': 'b4d363db94fd8a9928fa977745c76ff9',+ 'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e','fableloom-branch-node.md': '39a208c8cc593d0531af50760e3cf0da','fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661','fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670','fableloom-review.md': 'c26a641f6d0530caef7d1186c3b09937',- 'fableloom-outline-episode.md': '513b2b5b8fa98766852cdde7b87198c9',+ 'fableloom-outline-episode.md': '820b8c157c1977b34eb317e44236519e','fableloom-review-episode-outline.md': '8154b4c289b10268df8fd3c625bcdac2',+ 'fableloom-generate-series-plan.md': '27336d8c64e6193aecd1ba697f52315e',};const EXPECTED_PARTIAL_OLD = {'bible-deference.md': ['218f0e85643609ed85a12b1ccc7b5a8d'],diff --git a/server/lib/README.md b/server/lib/README.mdindex 3540e58420..94726180fa 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -37,7 +37,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fableLoomPlayback.js` | FableLoom node playback modes (`cut` auto-advances; `decision` loops while awaiting input), with the backward-compatible default. || `fableLoomParticipation.js` | FableLoom audience roles (helper vs protagonist), per-scene connection availability, prompt contracts, and backward-compatible defaults. || `fableLoomFormats.js` | FableLoom scene formats (`LOOM_FORMATS`, `asLoomFormat`, `sceneFormatContract`, …) — how a loom writes scene text, read by validation, the sanitizer, and every generative stage. |-| `fableLoomProduction.js` | FableLoom production batch planning and topological orchestration: ordered episode storyboard gates, DAG resolution, asset enumeration, execution stages, and exact-input provenance verification. |+| `fableLoomProduction.js` | FableLoom production batch planning and topological orchestration: explicit shared still/video render-format presets (16:9 default), ordered episode storyboard gates, DAG resolution, asset enumeration, execution stages, and exact-input provenance verification. || `fableLoomContinuity.js` | FableLoom episodic continuity review: multi-vector deterministic checks for visual entity bindings, convergence clarity, voice profile consistency/drift, pronunciation anchors, and playback safety. || `fableLoomOutline.js` | FableLoom story-first episode beat outlines: bounded log-lines, deterministic arc validation, and compact prompt rendering before teleplay expansion. || `fableLoomPlaytest.js` | FableLoom branching-playthrough harness: bounded exhaustive path enumeration, ending/loop/coverage diagnostics, aggregate loom reports, and compact traces for narrative-quality review. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 759f820b99..f248e5db4c 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -10364,7 +10364,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 808+ "line": 826}]},@@ -10375,7 +10375,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 832+ "line": 850}]},@@ -10386,7 +10386,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 827+ "line": 845}]},@@ -10397,7 +10397,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 861+ "line": 879}]},@@ -10408,7 +10408,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 846+ "line": 864}]},@@ -10419,7 +10419,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 823+ "line": 841}]},@@ -10430,7 +10430,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 751+ "line": 769}]},@@ -10463,7 +10463,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 619+ "line": 637}]},@@ -10474,7 +10474,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 757+ "line": 775}]},@@ -10485,7 +10485,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 742+ "line": 760}]},@@ -10507,7 +10507,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 738+ "line": 756}]},@@ -10518,7 +10518,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 641+ "line": 659}]},@@ -10529,7 +10529,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 719+ "line": 737}]},@@ -10540,7 +10540,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 700+ "line": 718}]},@@ -10551,7 +10551,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 652+ "line": 670}]},@@ -10562,7 +10562,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 680+ "line": 698}]},@@ -10705,7 +10705,7 @@"sources": [{"source": "server/routes/imageGen.js",- "line": 635+ "line": 653}]},@@ -22151,7 +22151,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 938+ "line": 940}]},@@ -22162,7 +22162,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1327+ "line": 1358}]},@@ -22173,7 +22173,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1303+ "line": 1334}]},@@ -22184,7 +22184,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1332+ "line": 1363}]},@@ -22195,7 +22195,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1361+ "line": 1392}]},@@ -22206,7 +22206,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1409+ "line": 1440}]},@@ -22217,7 +22217,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1381+ "line": 1412}]},@@ -22228,7 +22228,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1417+ "line": 1448}]},@@ -22239,7 +22239,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1413+ "line": 1444}]},@@ -22250,7 +22250,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 817+ "line": 819}]},@@ -22261,7 +22261,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 836+ "line": 838}]},@@ -22272,7 +22272,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1434+ "line": 1465}]},@@ -22283,7 +22283,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 455+ "line": 457}]},@@ -22294,7 +22294,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 459+ "line": 461}]},@@ -22305,7 +22305,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 527+ "line": 529}]},@@ -22316,7 +22316,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 780+ "line": 782}]},@@ -22327,7 +22327,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 765+ "line": 767}]},@@ -22338,7 +22338,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 668+ "line": 670}]},@@ -22349,7 +22349,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 748+ "line": 750}]},@@ -22360,7 +22360,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 497+ "line": 499}]},@@ -22371,7 +22371,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 499+ "line": 501}]},@@ -22382,7 +22382,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 493+ "line": 495}]},@@ -22393,7 +22393,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 405+ "line": 407}]},@@ -22404,7 +22404,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1451+ "line": 1482}]},@@ -22415,7 +22415,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 925+ "line": 927}]},@@ -22426,7 +22426,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 911+ "line": 913}]},@@ -22437,7 +22437,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 881+ "line": 883}]},@@ -22448,7 +22448,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 891+ "line": 893}]},@@ -22459,7 +22459,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1402+ "line": 1433}]},@@ -22470,7 +22470,7 @@"sources": [{"source": "server/routes/videoGen.js",- "line": 1440+ "line": 1471}]},diff --git a/server/lib/fableLoomOutline.js b/server/lib/fableLoomOutline.jsindex e1e04b970d..20be717000 100644--- a/server/lib/fableLoomOutline.js+++ b/server/lib/fableLoomOutline.js@@ -39,13 +39,45 @@ export const OUTLINE_ISSUE_CODES = Object.freeze({TELEPLAY_SCENE_MEMBERSHIP_MISMATCH: 'TELEPLAY_SCENE_MEMBERSHIP_MISMATCH',TELEPLAY_START_MISMATCH: 'TELEPLAY_START_MISMATCH',TELEPLAY_SCENE_CONTRACT_MISMATCH: 'TELEPLAY_SCENE_CONTRACT_MISMATCH',+ TELEPLAY_REPLACEMENT_PENDING: 'TELEPLAY_REPLACEMENT_PENDING',MISSING_OVERNIGHT_VOICEMAIL: 'MISSING_OVERNIGHT_VOICEMAIL',EMPTY_OVERNIGHT_VOICEMAIL: 'EMPTY_OVERNIGHT_VOICEMAIL',MISSING_NEXT_SEASON_TEASER: 'MISSING_NEXT_SEASON_TEASER',+ CHALLENGE_PHASE_MISSING: 'CHALLENGE_PHASE_MISSING',+ CHALLENGE_PATH_MISSING: 'CHALLENGE_PATH_MISSING',+ CHALLENGE_DECISION_INVALID: 'CHALLENGE_DECISION_INVALID',});+export const STORY_OUTLINE_TELEPLAY_SYNC_CODES = Object.freeze([+ OUTLINE_ISSUE_CODES.TELEPLAY_SCENE_MEMBERSHIP_MISMATCH,+ OUTLINE_ISSUE_CODES.TELEPLAY_START_MISMATCH,+ OUTLINE_ISSUE_CODES.TELEPLAY_SCENE_CONTRACT_MISMATCH,+]);++const storyOutlineTeleplaySyncCodeSet = new Set(STORY_OUTLINE_TELEPLAY_SYNC_CODES);++export const isStoryOutlineTeleplaySyncIssue = (issue) => (+ storyOutlineTeleplaySyncCodeSet.has(issue?.code)+);+const OUTLINE_STATUSES = new Set(['draft', 'valid', 'invalid']);+export const FABLELOOM_PLOT_POINT_KINDS = Object.freeze(['beat', 'challenge']);+export const FABLELOOM_CHALLENGE_PHASES = Object.freeze([+ 'setup', 'decision', 'success', 'failure', 'recovery',+]);+const challengePhaseSet = new Set(FABLELOOM_CHALLENGE_PHASES);++export const fableLoomPlotPointKind = (item) => (+ item?.kind === 'challenge'+ || (item?.kind == null && /^challenge\s*(?:[-—:]|$)/i.test(item?.title?.trim() || ''))+ ? 'challenge'+ : 'beat'+);++export const fableLoomEpisodeChallenges = (loom, episodeId) => asArray(loom?.seriesPlan?.plotPoints)+ .filter((item) => item?.episodeId === episodeId && fableLoomPlotPointKind(item) === 'challenge');+const uniqueKey = (candidate, index, seen) => {const base = isText(candidate)? candidate.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)@@ -110,6 +142,10 @@ export function sanitizeStoryOutline(raw, { participationMode = 'protagonist' }key,title: trimTo(scene?.title, LOOM_LIMITS.NODE_TITLE_MAX),summary: trimTo(scene?.summary, LOOM_LIMITS.OUTLINE_SUMMARY_MAX),+ plotPointId: isText(scene?.plotPointId)+ ? scene.plotPointId.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)+ : null,+ challengePhase: challengePhaseSet.has(scene?.challengePhase) ? scene.challengePhase : null,playbackMode: scene?.playbackMode === 'cut' ? 'cut' : 'decision',audienceConnection: scene?.audienceConnection === 'connected' ? 'connected' : 'disconnected',protagonistPresence: FABLELOOM_PROTAGONIST_PRESENCE.includes(scene?.protagonistPresence)@@ -140,7 +176,7 @@ const outlineIssue = (issues, code, severity, message, extra = {}) => {/** Deterministic validation for the log-line graph, independent of an LLM. */export function analyzeStoryOutline(outline, {- participationMode = 'protagonist', requireAudienceIntroduction = false,+ participationMode = 'protagonist', requireAudienceIntroduction = false, challenges = [],} = {}) {const scenes = asArray(outline?.scenes);const byKey = new Map(scenes.map((scene) => [scene.key, scene]));@@ -287,6 +323,72 @@ export function analyzeStoryOutline(outline, {});}+ const pathExists = (fromScenes, toScenes) => {+ const targets = new Set(toScenes.map((scene) => scene.key));+ const queue = fromScenes.map((scene) => scene.key);+ const seen = new Set();+ while (queue.length) {+ const key = queue.shift();+ if (seen.has(key)) continue;+ seen.add(key);+ if (targets.has(key)) return true;+ for (const transition of asArray(byKey.get(key)?.transitions)) {+ if (byKey.has(transition.targetKey) && !seen.has(transition.targetKey)) {+ queue.push(transition.targetKey);+ }+ }+ }+ return false;+ };+ let readyChallengeCount = 0;+ for (const challenge of asArray(challenges)) {+ const label = challenge.title || challenge.id || 'Untitled challenge';+ const mapped = scenes.filter((scene) => scene.plotPointId === challenge.id);+ const byPhase = Object.fromEntries(FABLELOOM_CHALLENGE_PHASES.map((phase) => [+ phase, mapped.filter((scene) => scene.challengePhase === phase),+ ]));+ let challengeReady = true;+ for (const phase of FABLELOOM_CHALLENGE_PHASES) {+ if (byPhase[phase].length) continue;+ challengeReady = false;+ push(+ OUTLINE_ISSUE_CODES.CHALLENGE_PHASE_MISSING,+ 'error',+ `Playable challenge "${label}" needs a mapped ${phase} beat.`,+ );+ }+ const invalidDecision = byPhase.decision.find((scene) => scene.playbackMode !== 'decision'+ || asArray(scene.transitions).length < 2);+ if (invalidDecision) {+ challengeReady = false;+ push(+ OUTLINE_ISSUE_CODES.CHALLENGE_DECISION_INVALID,+ 'error',+ `Playable challenge "${label}" needs a decision-loop beat with at least two viewer paths.`,+ { sceneKey: invalidDecision.key },+ );+ }+ const requiredPaths = [+ ['setup', 'decision'],+ ['decision', 'success'],+ ['decision', 'failure'],+ ['success', 'recovery'],+ ['failure', 'recovery'],+ ];+ for (const [fromPhase, toPhase] of requiredPaths) {+ if (!byPhase[fromPhase].length || !byPhase[toPhase].length+ || pathExists(byPhase[fromPhase], byPhase[toPhase])) continue;+ challengeReady = false;+ push(+ OUTLINE_ISSUE_CODES.CHALLENGE_PATH_MISSING,+ 'error',+ `Playable challenge "${label}" has no path from its ${fromPhase} beat to its ${toPhase} beat.`,+ { sceneKey: byPhase[fromPhase][0]?.key },+ );+ }+ if (challengeReady) readyChallengeCount += 1;+ }+const stats = {sceneCount: scenes.length,automaticCutCount: scenes.filter((scene) => !scene.isEnding && scene.playbackMode === 'cut').length,@@ -297,6 +399,8 @@ export function analyzeStoryOutline(outline, {maxDepth: depthByKey.size ? Math.max(...depthByKey.values()) : 0,errorCount: issues.filter((issue) => issue.severity === 'error').length,warningCount: issues.filter((issue) => issue.severity === 'warning').length,+ challengeCount: asArray(challenges).length,+ readyChallengeCount,};return { issues, stats };}@@ -342,6 +446,8 @@ export function analyzeStoryOutlineTeleplaySync(episode, outline, {? 'offscreen': 'onscreen');const semanticFieldsMatch = scene.title === node.title+ && (scene.plotPointId || null) === (node.plotPointId || null)+ && (scene.challengePhase || null) === (node.challengePhase || null)&& scene.playbackMode === node.playbackMode&& scene.audienceConnection === node.audienceConnection&& scene.protagonistPresence === expectedProtagonistPresence@@ -370,7 +476,7 @@ export function analyzeStoryOutlineTeleplaySync(episode, outline, {* episode is expanded until the whole series has a validated beat arc and its* optional delivery handoffs are authored.*/-export function analyzeSeriesStoryOutlines(loom) {+export function analyzeSeriesStoryOutlines(loom, { replacingEpisodeId = null } = {}) {const episodes = asArray(loom?.episodes);const issues = [];const readyEpisodeIds = new Set();@@ -392,6 +498,7 @@ export function analyzeSeriesStoryOutlines(loom) {const validation = analyzeStoryOutline(episode.storyOutline, {participationMode: loom?.participationMode,requireAudienceIntroduction: index === 0,+ challenges: fableLoomEpisodeChallenges(loom, episode.id),});validation.issues.forEach((issue) => {push(issue.code, issue.severity, `Episode ${episode.number || index + 1}: ${issue.message}`, {@@ -403,25 +510,38 @@ export function analyzeSeriesStoryOutlines(loom) {const teleplaySync = analyzeStoryOutlineTeleplaySync(episode, episode.storyOutline, {participationMode: loom?.participationMode,});- teleplaySync.issues.forEach((issue) => {+ const replacingThisEpisode = episode.id === replacingEpisodeId+ && validation.stats.errorCount === 0+ && !teleplaySync.stats.matches;+ if (replacingThisEpisode) {push(- issue.code,- issue.severity,- `Episode ${episode.number || index + 1}: ${issue.message}`,- {- episodeId: episode.id,- ...(issue.sceneKey ? { sceneKey: issue.sceneKey } : {}),- },+ OUTLINE_ISSUE_CODES.TELEPLAY_REPLACEMENT_PENDING,+ 'warning',+ `Episode ${episode.number || index + 1}'s validated beat outline will replace its older teleplay scenes.`,+ { episodeId: episode.id },);- });- if (episode.storyOutline.validation?.status !== 'valid') {+ } else {+ teleplaySync.issues.forEach((issue) => {+ push(+ issue.code,+ issue.severity,+ `Episode ${episode.number || index + 1}: ${issue.message}`,+ {+ episodeId: episode.id,+ ...(issue.sceneKey ? { sceneKey: issue.sceneKey } : {}),+ },+ );+ });+ }+ if (episode.storyOutline.validation?.status !== 'valid' && !replacingThisEpisode) {push(OUTLINE_ISSUE_CODES.EPISODE_OUTLINE_NOT_VALIDATED,'error',`Episode ${episode.number || index + 1}'s beat outline must be validated before teleplay expansion.`,{ episodeId: episode.id },);- } else if (validation.stats.errorCount === 0 && teleplaySync.stats.matches) {+ } else if (validation.stats.errorCount === 0+ && (teleplaySync.stats.matches || replacingThisEpisode)) {readyEpisodeIds.add(episode.id);}});@@ -487,6 +607,8 @@ export function describeStoryOutlineForPrompt(outline) {scene.isEnding ? null : scene.playbackMode === 'cut' ? 'AUTO CUT' : 'DECISION',scene.audienceConnection === 'connected' ? 'AUDIENCE CONNECTED' : 'AUDIENCE DISCONNECTED',scene.protagonistPresence === 'offscreen' ? 'PROTAGONIST OFF-SCREEN' : 'PROTAGONIST ON-SCREEN',+ scene.plotPointId ? `PLOT POINT: ${scene.plotPointId}` : null,+ scene.challengePhase ? `CHALLENGE ${scene.challengePhase.toUpperCase()}` : null,].filter(Boolean);const paths = asArray(scene.transitions).map((transition) => {const target = byKey.get(transition.targetKey);diff --git a/server/lib/fableLoomOutline.test.js b/server/lib/fableLoomOutline.test.jsindex 24ea025c34..8a43be8438 100644--- a/server/lib/fableLoomOutline.test.js+++ b/server/lib/fableLoomOutline.test.js@@ -88,6 +88,55 @@ describe('FableLoom story beat outlines', () => {expect(result.stats.errorCount).toBeGreaterThan(0);});+ it('requires every playable challenge to map setup, decision, outcomes, and recovery into reachable scenes', () => {+ const challenge = { id: 'plot-lock', kind: 'challenge', title: 'Open the sealed door' };+ const challengeOutline = sanitizeStoryOutline({+ startKey: 'setup',+ scenes: [+ {+ key: 'setup', title: 'The keypad', summary: 'A prior clue makes the sealed keypad actionable.',+ plotPointId: challenge.id, challengePhase: 'setup', playbackMode: 'cut',+ transitions: [{ targetKey: 'decision', intent: 'try the keypad' }],+ },+ {+ key: 'decision', title: 'Choose the code', summary: 'The viewer chooses which remembered code to enter.',+ plotPointId: challenge.id, challengePhase: 'decision', playbackMode: 'decision',+ transitions: [+ { targetKey: 'success', intent: 'enter the remembered code' },+ { targetKey: 'failure', intent: 'guess under pressure' },+ ],+ },+ {+ key: 'success', title: 'The lock opens', summary: 'The correct code opens the door quietly.',+ plotPointId: challenge.id, challengePhase: 'success', playbackMode: 'cut',+ transitions: [{ targetKey: 'recovery', intent: 'slip through' }],+ },+ {+ key: 'failure', title: 'The alarm chirps', summary: 'The wrong code alerts a guard but leaves an escape route.',+ plotPointId: challenge.id, challengePhase: 'failure', playbackMode: 'cut',+ transitions: [{ targetKey: 'recovery', intent: 'improvise a distraction' }],+ },+ {+ key: 'recovery', title: 'Beyond the door', summary: 'Both routes continue with distinct costs into the next blockade.',+ plotPointId: challenge.id, challengePhase: 'recovery', playbackMode: 'cut',+ transitions: [{ targetKey: 'ending', intent: 'move deeper inside' }],+ },+ {+ key: 'ending', title: 'Inside', summary: 'The viewer gets the character safely inside.',+ isEnding: true, endingLabel: 'Through the first blockade', transitions: [],+ },+ ],+ });++ const ready = analyzeStoryOutline(challengeOutline, { challenges: [challenge] });+ expect(ready.stats).toMatchObject({ challengeCount: 1, readyChallengeCount: 1, errorCount: 0 });++ const missingFailure = structuredClone(challengeOutline);+ missingFailure.scenes.find((scene) => scene.key === 'failure').challengePhase = null;+ expect(analyzeStoryOutline(missingFailure, { challenges: [challenge] }).issues)+ .toContainEqual(expect.objectContaining({ code: 'CHALLENGE_PHASE_MISSING' }));+ });+it('keeps outline rendering compact for the AI prompt', () => {const outline = sanitizeStoryOutline(validOutline);const digest = describeStoryOutlineForPrompt(outline);@@ -170,4 +219,48 @@ describe('FableLoom story beat outlines', () => {}));expect(series.stats).toMatchObject({ ready: false, readyEpisodeCount: 0 });});++ it('allows one structurally sound outline to replace its older teleplay explicitly', () => {+ const storyOutline = {+ ...sanitizeStoryOutline(validOutline),+ validation: {+ status: 'invalid',+ issues: [{+ code: 'TELEPLAY_SCENE_CONTRACT_MISMATCH',+ severity: 'error',+ message: 'The edited beat differs from the old scene.',+ sceneKey: 's1',+ }],+ },+ };+ const episode = {+ id: 'ep-1',+ number: 1,+ startNodeId: 's1',+ storyOutline,+ nodes: storyOutline.scenes.map((scene) => ({+ id: scene.key,+ title: scene.key === 's1' ? 'Old signal' : scene.title,+ playbackMode: scene.playbackMode,+ audienceConnection: scene.audienceConnection,+ protagonistPresence: scene.protagonistPresence,+ isEnding: scene.isEnding,+ endingLabel: scene.endingLabel,+ transitions: scene.transitions.map((item) => ({+ targetNodeId: item.targetKey,+ intent: item.intent,+ })),+ })),+ };+ const loom = { participationMode: 'protagonist', episodes: [episode], seriesPlan: {} };++ expect(analyzeSeriesStoryOutlines(loom).stats.ready).toBe(false);+ const replacement = analyzeSeriesStoryOutlines(loom, { replacingEpisodeId: episode.id });++ expect(replacement.stats).toMatchObject({ ready: true, readyEpisodeCount: 1, errorCount: 0 });+ expect(replacement.issues).toContainEqual(expect.objectContaining({+ code: 'TELEPLAY_REPLACEMENT_PENDING',+ severity: 'warning',+ }));+ });});diff --git a/server/lib/fableLoomProduction.js b/server/lib/fableLoomProduction.jsindex 8cf37a8d35..cdd582cd81 100644--- a/server/lib/fableLoomProduction.js+++ b/server/lib/fableLoomProduction.js@@ -12,6 +12,35 @@ import { validateAudioOccupancy } from './fableLoomPlayback.js';export const FABLELOOM_PRODUCTION_MODES = Object.freeze(['current_canon', 'exact_inputs']);export const FABLELOOM_PRODUCTION_MODE_DEFAULT = 'current_canon';+// One format owns both storyboard stills and motion renders so an episode+// cannot accidentally mix a portrait image with a landscape clip. These are+// deliberately concrete render sizes, not ratio labels alone: every provider+// receives an explicit width/height instead of falling through to its own+// (often square or portrait) default. 16:9 is the FableLoom default because the+// hosted experience is composed as a cinematic screen.+export const FABLELOOM_RENDER_FORMATS = Object.freeze([+ Object.freeze({ formatId: 'landscape-16-9', label: '16:9 landscape', aspectRatio: '16:9', width: 1024, height: 576 }),+ Object.freeze({ formatId: 'portrait-9-16', label: '9:16 portrait', aspectRatio: '9:16', width: 576, height: 1024 }),+ Object.freeze({ formatId: 'square-1-1', label: '1:1 square', aspectRatio: '1:1', width: 1024, height: 1024 }),+ Object.freeze({ formatId: 'classic-4-3', label: '4:3 landscape', aspectRatio: '4:3', width: 1024, height: 768 }),+]);+export const FABLELOOM_RENDER_FORMAT_IDS = Object.freeze(+ FABLELOOM_RENDER_FORMATS.map((format) => format.formatId),+);+export const FABLELOOM_DEFAULT_RENDER_FORMAT_ID = 'landscape-16-9';++export function asFableLoomRenderSettings(raw) {+ const requestedId = typeof raw === 'string' ? raw : raw?.formatId;+ const selected = FABLELOOM_RENDER_FORMATS.find((format) => format.formatId === requestedId)+ || FABLELOOM_RENDER_FORMATS.find((format) => format.formatId === FABLELOOM_DEFAULT_RENDER_FORMAT_ID);+ return {+ formatId: selected.formatId,+ aspectRatio: selected.aspectRatio,+ width: selected.width,+ height: selected.height,+ };+}+export const FABLELOOM_ASSET_TYPES = Object.freeze(['image','video_entry',@@ -23,6 +52,56 @@ export const FABLELOOM_ASSET_TYPES = Object.freeze([const isStr = (v) => typeof v === 'string' && v.trim().length > 0;const isLockedCanon = (node) => Boolean(node?.visualCanon && node.visualCanon.mode !== 'draft');+const EXACT_RENDER_KEYS = Object.freeze({+ image: Object.freeze({+ local: Object.freeze(['width', 'height', 'aspectRatio', 'steps', 'guidance', 'quantize', 'seed']),+ cloud: Object.freeze(['width', 'height', 'aspectRatio', 'mode']),+ }),+ video: Object.freeze({+ local: Object.freeze([+ 'width', 'height', 'aspectRatio', 'numFrames', 'fps', 'steps', 'guidanceScale', 'seed', 'mode',+ 'tiling', 'disableAudio',+ ]),+ cloud: Object.freeze(['width', 'height', 'aspectRatio', 'mode', 'videoMode']),+ }),+});++const validRenderParameter = (key, value) => {+ if (['aspectRatio', 'mode', 'videoMode', 'tiling'].includes(key)) return isStr(value);+ if (key === 'disableAudio') return typeof value === 'boolean';+ if (key === 'quantize') return isStr(value) || Number.isFinite(value);+ if (!Number.isFinite(value)) return false;+ if (['seed', 'guidance', 'guidanceScale'].includes(key)) return value >= 0;+ return value > 0;+};++/** Validate the atomic render tuple required for exact-input reproduction. */+export function exactRenderParameterIssues(recordedProvenance) {+ const capability = recordedProvenance?.capability || {};+ const kind = capability.kind;+ const backendFamily = capability.backend === 'local' ? 'local' : 'cloud';+ const required = EXACT_RENDER_KEYS[kind]?.[backendFamily];+ if (!required) return ['Recorded visual conditioning has no supported render capability.'];+ const parameters = recordedProvenance?.render?.parameters;+ if (!parameters || typeof parameters !== 'object') {+ return ['Recorded visual conditioning has no effective render parameters.'];+ }+ const issues = required+ .filter((key) => !validRenderParameter(key, parameters[key]))+ .map((key) => `Recorded ${kind} render parameter "${key}" is missing or invalid.`);+ if (issues.length) return issues;+ const [ratioWidth, ratioHeight] = parameters.aspectRatio.split(':').map(Number);+ if (!(ratioWidth > 0 && ratioHeight > 0)) {+ return ['Recorded render aspectRatio is invalid.'];+ }+ const recordedRatio = parameters.width / parameters.height;+ const declaredRatio = ratioWidth / ratioHeight;+ if (Math.abs(recordedRatio - declaredRatio) / declaredRatio > 0.02) {+ return ['Recorded render width, height, and aspectRatio do not describe the same format.'];+ }+ return [];+}+/*** Compute the topological ordering of reachable nodes in an episode graph,* respecting graph convergence and path-specific predecessors.@@ -247,6 +326,7 @@ export function verifyExactInputProvenance(recordedProvenance, {}}}+ errors.push(...exactRenderParameterIssues(recordedProvenance));const bindings = recordedProvenance.bindings;if (!bindings || typeof bindings !== 'object') {@@ -619,7 +699,9 @@ export function buildEpisodeProductionPlan({temporalSourceNodeId,dependencies: imageDependencies,existingAssetId: existingStill,- status: existingStill && nodeBlockers.length === 0 ? 'already_rendered' : (imageHasPrompt && nodeBlockers.length === 0 ? 'ready' : 'blocked'),+ status: existingStill && nodeBlockers.length === 0 && effectiveMode !== 'exact_inputs'+ ? 'already_rendered'+ : (imageHasPrompt && nodeBlockers.length === 0 ? 'ready' : 'blocked'),readiness: {ready: imageReady,reasons: imageBlockers,@@ -649,7 +731,9 @@ export function buildEpisodeProductionPlan({cameraMovement: node.cameraMovement || null,dependencies: [imageAssetId],existingAssetId: existingEntryVideo,- status: existingEntryVideo && nodeBlockers.length === 0 ? 'already_rendered' : (videoReady ? 'ready' : 'blocked'),+ status: existingEntryVideo && nodeBlockers.length === 0 && effectiveMode !== 'exact_inputs'+ ? 'already_rendered'+ : (videoReady ? 'ready' : 'blocked'),readiness: {ready: videoReady,reasons: videoBlockers,@@ -686,7 +770,9 @@ export function buildEpisodeProductionPlan({cameraMovement: node.cameraMovement || null,dependencies: [imageAssetId],existingAssetId: existingHold,- status: existingHold && holdBlockers.length === 0 ? 'already_rendered' : (videoHasPrompt && holdBlockers.length === 0 ? 'ready' : 'blocked'),+ status: existingHold && holdBlockers.length === 0 && effectiveMode !== 'exact_inputs'+ ? 'already_rendered'+ : (videoHasPrompt && holdBlockers.length === 0 ? 'ready' : 'blocked'),readiness: {ready: videoHasPrompt && holdBlockers.length === 0,reasons: videoHasPrompt ? holdBlockers : [...holdBlockers, 'Scene has neither videoPrompt nor prose for video.'],@@ -717,7 +803,9 @@ export function buildEpisodeProductionPlan({prompt: tr.description || videoPrompt,dependencies: [imageAssetId],existingAssetId: existingExit,- status: existingExit && exitBlockers.length === 0 ? 'already_rendered' : (exitHasPrompt && exitBlockers.length === 0 ? 'ready' : 'blocked'),+ status: existingExit && exitBlockers.length === 0 && effectiveMode !== 'exact_inputs'+ ? 'already_rendered'+ : (exitHasPrompt && exitBlockers.length === 0 ? 'ready' : 'blocked'),readiness: {ready: exitHasPrompt && exitBlockers.length === 0,reasons: exitBlockers,diff --git a/server/lib/fableLoomProduction.test.js b/server/lib/fableLoomProduction.test.jsindex f11fa6b19c..db1049d1a7 100644--- a/server/lib/fableLoomProduction.test.js+++ b/server/lib/fableLoomProduction.test.js@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import {+ asFableLoomRenderSettings,buildEpisodeProductionPlan,computeTopologicalNodeOrder,inspectEpisodeProductionOrder,@@ -60,6 +61,21 @@ describe('fableLoomProduction', () => {],};+ it('defaults every loom to an explicit 16:9 landscape render format', () => {+ expect(asFableLoomRenderSettings()).toEqual({+ formatId: 'landscape-16-9',+ aspectRatio: '16:9',+ width: 1024,+ height: 576,+ });+ expect(asFableLoomRenderSettings({ formatId: 'portrait-9-16' })).toMatchObject({+ aspectRatio: '9:16', width: 576, height: 1024,+ });+ expect(asFableLoomRenderSettings({ formatId: 'unknown' })).toMatchObject({+ aspectRatio: '16:9', width: 1024, height: 576,+ });+ });+it('computes topological node ordering and detects convergence', () => {const topo = computeTopologicalNodeOrder(sampleEpisode);expect(topo.orderedNodes.map((n) => n.id)).toEqual(['node-1', 'node-2', 'node-3', 'node-4']);@@ -233,6 +249,17 @@ describe('fableLoomProduction', () => {adapters: [],omitted: [],warnings: [],+ render: {+ parameters: {+ width: 1024,+ height: 576,+ aspectRatio: '16:9',+ steps: 28,+ guidance: 3.5,+ quantize: '8',+ seed: 42,+ },+ },};const baseOptions = {universe: { id: 'univ-1', characters: [], places: [], objects: [] },@@ -241,6 +268,10 @@ describe('fableLoomProduction', () => {};expect(verifyExactInputProvenance(visualProvenance, baseOptions).valid).toBe(true);+ const missingRenderTuple = structuredClone(visualProvenance);+ delete missingRenderTuple.render.parameters.seed;+ expect(verifyExactInputProvenance(missingRenderTuple, baseOptions).errors)+ .toContain('Recorded image render parameter "seed" is missing or invalid.');expect(verifyExactInputProvenance(visualProvenance, {...baseOptions,availableImageModels: [],diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex c915302d45..720c60bbeb 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -21,7 +21,12 @@ import {import {FABLELOOM_ASSET_TYPES,FABLELOOM_PRODUCTION_MODES,+ FABLELOOM_RENDER_FORMAT_IDS,} from './fableLoomProduction.js';+import {+ FABLELOOM_CHALLENGE_PHASES,+ FABLELOOM_PLOT_POINT_KINDS,+} from './fableLoomOutline.js';import { FABLELOOM_PLAYTEST_LIMITS } from './fableLoomPlaytest.js';import { EFFORT_LEVELS } from './providerModels.js';import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';@@ -44,6 +49,14 @@ 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 renderSettings = z.object({+ formatId: z.enum(FABLELOOM_RENDER_FORMAT_IDS),+});+const productionStatus = z.object({+ editorialApprovedAt: z.string().max(80).nullable().optional(),+ editorialApprovalSource: z.enum(['manual', 'autopilot']).nullable().optional(),+ deliveryApprovedAt: z.string().max(80).nullable().optional(),+});const planItemId = z.string().min(1).max(80).optional();const planEpisodeId = z.string().min(1).max(80).nullable().optional();const planItemFields = {@@ -55,6 +68,7 @@ const seriesPlan = z.object({storyArc: z.string().max(LOOM_LIMITS.STORY_ARC_MAX),plotPoints: z.array(z.object({...planItemFields,+ kind: z.enum(FABLELOOM_PLOT_POINT_KINDS).optional(),episodeId: planEpisodeId,})).max(LOOM_LIMITS.PLAN_ITEMS_MAX),sideQuests: z.array(z.object({@@ -104,6 +118,8 @@ const storyOutline = z.object({key: z.string().max(LOOM_LIMITS.OUTLINE_KEY_MAX),title: z.string().max(LOOM_LIMITS.NODE_TITLE_MAX).optional(),summary: z.string().max(LOOM_LIMITS.OUTLINE_SUMMARY_MAX).optional(),+ plotPointId: z.string().max(LOOM_LIMITS.OUTLINE_KEY_MAX).nullable().optional(),+ challengePhase: z.enum(FABLELOOM_CHALLENGE_PHASES).nullable().optional(),playbackMode: z.enum(['cut', 'decision']).optional(),audienceConnection: z.enum(['connected', 'disconnected']).optional(),protagonistPresence: z.enum(FABLELOOM_PROTAGONIST_PRESENCE).optional(),@@ -131,6 +147,7 @@ export const loomCreateSchema = z.object({audienceCommunicationMedium: audienceCommunicationMedium.optional(),format: format.optional(),playSettings: playSettings.optional(),+ renderSettings: renderSettings.optional(),seriesPlan: seriesPlan.optional(),protagonistCharacterId: refId.optional(),protagonistWardrobeId: refId.optional(),@@ -148,6 +165,8 @@ export const loomPatchSchema = z.object({audienceCommunicationMedium: audienceCommunicationMedium.optional(),format: format.optional(),playSettings: playSettings.optional(),+ renderSettings: renderSettings.optional(),+ productionStatus: productionStatus.optional(),seriesPlan: seriesPlan.optional(),protagonistCharacterId: refId.optional(),protagonistWardrobeId: refId.optional(),@@ -255,6 +274,8 @@ export const interactionWindowSchema = z.object({const nodeFields = {title: z.string().max(LOOM_LIMITS.NODE_TITLE_MAX).optional(),prose: z.string().max(LOOM_LIMITS.PROSE_MAX).optional(),+ plotPointId: z.string().max(LOOM_LIMITS.OUTLINE_KEY_MAX).nullable().optional(),+ challengePhase: z.enum(FABLELOOM_CHALLENGE_PHASES).nullable().optional(),imagePrompt: z.string().max(LOOM_LIMITS.IMAGE_PROMPT_MAX).optional(),videoPrompt: z.string().max(LOOM_LIMITS.VIDEO_PROMPT_MAX).optional(),cameraMovement: z.string().max(LOOM_LIMITS.CAMERA_MOVEMENT_MAX).optional(),diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 491a0e8e0c..696019e7c3 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -365,7 +365,13 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// side-device off-screen. A v3 peer would silently strip those fields on a// whole-record round trip and could restore wardrobe drift or put a removed// protagonist back into a scene.- fableLoom: 4,+ // v5 = one loom-level render format pins the aspect ratio and concrete+ // dimensions shared by storyboard stills and motion clips; plot points and+ // scenes gained durable playable-challenge kinds/phase mappings; and durable+ // editorial/final-delivery sign-offs let the ordered workflow survive a+ // reload. A v4 peer would strip those choices and silently reopen completed+ // gates, erase challenge-to-scene mapping, or reintroduce mixed geometry.+ fableLoom: 5,// v1 = Creative Director projects (PostgreSQL `creative_director_projects`)// federated via the per-record peer-sync push pipeline (record kind// `creativeDirectorProject`, sync category `creativeDirectorProjects`, #1564).diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex df379bc35a..4ddf3a0d70 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -42,10 +42,10 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {expect(PORTOS_SCHEMA_VERSIONS.mediaCollections).toBe(1);});- it('version-gates the canonical FableLoom protagonist continuity shape', () => {- // v4 adds the loom-level protagonist/wardrobe pin and per-scene presence;- // migration 319 upgrades the shipped prompt contract alongside it.- expect(PORTOS_SCHEMA_VERSIONS.fableLoom).toBe(4);+ it('version-gates the persisted FableLoom render-format shape', () => {+ // v5 adds renderSettings. Older peers stay on the v4 protagonist-+ // continuity shape until they advertise support for the render contract.+ expect(PORTOS_SCHEMA_VERSIONS.fableLoom).toBe(5);});it('version-gates the additive Creative Commission taste brief shape', () => {diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex dd08b321b2..140c7b7fce 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -45,7 +45,7 @@ import { getSettings } from '../services/settings.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';import { collectRemoteInputAssets } from '../services/federatedMedia/inputAssets.js';import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';-import { inspectEpisodeProductionOrder } from '../lib/fableLoomProduction.js';+import { asFableLoomRenderSettings, inspectEpisodeProductionOrder } from '../lib/fableLoomProduction.js';import { attachNodeImage, getLoom } from '../services/fableLoom/records.js';import {compileFableLoomVisualRequest, fableLoomImageCapabilities,@@ -402,6 +402,12 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {if (params.fableLoom) {const taggedLoom = await getLoom(params.fableLoom.loomId);const taggedEpisode = taggedLoom?.episodes?.find((episode) => episode.id === params.fableLoom.episodeId);+ const renderSettings = taggedLoom ? asFableLoomRenderSettings(taggedLoom.renderSettings) : null;+ if (renderSettings) {+ params.width = renderSettings.width;+ params.height = renderSettings.height;+ params.aspectRatio = renderSettings.aspectRatio;+ }if (taggedLoom && taggedEpisode) {const episodeOrder = inspectEpisodeProductionOrder(taggedLoom, taggedEpisode);if (!episodeOrder.ready) {@@ -440,7 +446,19 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {params.loraFilenames = compiled.loraFilenames;params.loraPaths = [];params.loraScales = compiled.loraScales;- params.visualConditioning = compiled.visualConditioning;+ params.visualConditioning = compiled.visualConditioning ? {+ ...compiled.visualConditioning,+ render: {+ provider: providerMode,+ modelId: model?.id || null,+ modelRevision: model?.revision || null,+ parameters: {+ width: params.width,+ height: params.height,+ ...(params.aspectRatio ? { aspectRatio: params.aspectRatio } : {}),+ },+ },+ } : null;}}diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex c19326b097..6e4bbeee4c 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -251,6 +251,11 @@ describe('Image Gen Routes', () => {});it('durably attaches a synchronous FableLoom scene render', async () => {+ getLoom.mockResolvedValueOnce({+ id: 'loom-1',+ renderSettings: { formatId: 'landscape-16-9' },+ episodes: [{ id: 'ep-1', number: 1, startNodeId: 'node-1', nodes: [{ id: 'node-1', transitions: [] }] }],+ });imageGen.generateImage.mockResolvedValue({generationId: 'gen-scene-001',filename: 'scene.png',@@ -269,8 +274,19 @@ describe('Image Gen Routes', () => {'loom-1','ep-1','node-1',- { filename: 'scene.png', jobId: 'gen-scene-001', visualConditioning: compiledVisual },+ {+ filename: 'scene.png',+ jobId: 'gen-scene-001',+ visualConditioning: expect.objectContaining({+ render: expect.objectContaining({+ parameters: { width: 1024, height: 576, aspectRatio: '16:9' },+ }),+ }),+ },);+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({+ width: 1024, height: 576, aspectRatio: '16:9',+ }));expect(compileFableLoomVisualRequest).toHaveBeenCalledWith(expect.objectContaining({tag: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' }, kind: 'image',}));diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex bf439d1095..f9b231e269 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -79,6 +79,8 @@ import { detectSystemCapabilities, withHardwareCompatibility } from '../lib/systimport {compileFableLoomVisualRequest, fableLoomVideoCapabilities,} from '../services/fableLoom/visualConditioning.js';+import { getLoom } from '../services/fableLoom/records.js';+import { asFableLoomRenderSettings } from '../lib/fableLoomProduction.js';const router = Router();@@ -947,6 +949,18 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {failValidation(parsed);}const body = parsed.data;+ let fableLoomRenderSettings = null;+ if (body.fableLoom) {+ const taggedLoom = await getLoom(body.fableLoom.loomId).catch(async (error) => {+ await cleanupMultipartTemp(uploads);+ throw error;+ });+ if (taggedLoom) {+ fableLoomRenderSettings = asFableLoomRenderSettings(taggedLoom.renderSettings);+ body.width = fableLoomRenderSettings.width;+ body.height = fableLoomRenderSettings.height;+ }+ }// Federated render (#4348): submit to the selected peer instead of running// locally. Handled BEFORE prepareVideoGenParams, which resolves this// machine's backend and stages uploads a remote render can never use.@@ -1085,7 +1099,20 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {prepared.mode = 'text';}prepared.sourceImagePath = compiled.sourceImagePath;- body.visualConditioning = compiled.visualConditioning;+ const renderSettings = fableLoomRenderSettings || asFableLoomRenderSettings();+ body.visualConditioning = compiled.visualConditioning ? {+ ...compiled.visualConditioning,+ render: {+ provider: backend,+ modelId: conditioningModel?.id || null,+ modelRevision: conditioningModel?.revision || null,+ parameters: {+ width: body.width,+ height: body.height,+ aspectRatio: renderSettings.aspectRatio,+ },+ },+ } : null;}}@@ -1107,7 +1134,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {// into its mode selector.videoMode: sourceImagePath ? 'image' : 'text',grokPath: g.grokPath,- aspectRatio: g.aspectRatio,+ aspectRatio: body.visualConditioning?.render?.parameters?.aspectRatio || g.aspectRatio,prompt: body.prompt,negativePrompt: body.negativePrompt || '',width: body.width,@@ -1117,6 +1144,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {uploadedTempPath,...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),+ ...(body.visualConditioning ? { visualConditioning: body.visualConditioning } : {}),});return res.json({ jobId, generationId: jobId, filename: `${jobId}.mp4`, model: 'grok', mode: 'grok', status, position });}@@ -1137,6 +1165,9 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {modelId: body.modelId,width: body.width,height: body.height,+ ...(body.visualConditioning?.render?.parameters?.aspectRatio+ ? { aspectRatio: body.visualConditioning.render.parameters.aspectRatio }+ : {}),// Duration-driven A2V models derive this from ffprobe over the staged audio;// every other request passes the caller's value through unchanged.numFrames: effectiveNumFrames,diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex ccc23d5921..59638b7925 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -24,10 +24,12 @@ const compileFableLoomVisualRequest = vi.hoisted(() => vi.fn(async ({ authoredPrvisualConditioning: compiledVisual,})));const fableLoomVideoCapabilities = vi.hoisted(() => vi.fn(() => ({ version: 1, kind: 'video' })));+const getLoom = vi.hoisted(() => vi.fn(async () => null));vi.mock('../services/fableLoom/visualConditioning.js', () => ({compileFableLoomVisualRequest,fableLoomVideoCapabilities,}));+vi.mock('../services/fableLoom/records.js', () => ({ getLoom }));const installProcess = vi.hoisted(() => {const spawn = vi.fn();@@ -1093,6 +1095,10 @@ describe('videoGen routes', () => {});it('forwards a fableLoom i2v tag into job.params alongside the resolved frame', async () => {+ getLoom.mockResolvedValueOnce({+ id: 'loom-1',+ renderSettings: { formatId: 'portrait-9-16' },+ });const r = await request(app).post('/api/video-gen/').send({prompt: 'the gate slowly opens',mode: 'image',@@ -1104,8 +1110,15 @@ describe('videoGen routes', () => {kind: 'video',params: expect.objectContaining({sourceImagePath: '/mock/images/scene-image.png',+ width: 576,+ height: 1024,+ aspectRatio: '9:16',fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' },- visualConditioning: compiledVisual,+ visualConditioning: expect.objectContaining({+ render: expect.objectContaining({+ parameters: { width: 576, height: 1024, aspectRatio: '9:16' },+ }),+ }),}),}));expect(compileFableLoomVisualRequest).toHaveBeenCalledWith(expect.objectContaining({@@ -2126,6 +2139,22 @@ describe('videoGen routes', () => {// "durable survives" assertion below from being satisfied by a temp unlink.const durableUnlinks = () => unlinkedPaths().filter((p) => /^[\\/]mock[\\/]uploads[\\/]/.test(p));+ it('drops multipart temp files when FableLoom render settings cannot be loaded', async () => {+ getLoom.mockRejectedValueOnce(new Error('record store unavailable'));+ setPendingUpload(sourceUpload);++ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'the threshold opens',+ mode: 'image',+ fableLoom: JSON.stringify({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' }),+ });++ expect(r.status).toBe(500);+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ expect(unlinkedPaths()).toContain(sourceUpload.path);+ expect(durableUnlinks()).toEqual([]);+ });+it('unlinks the half-written destination AND every earlier staged copy when copyFile rejects', async () => {// sourceImage stages fine, audioFile's copy blows up — the failure has// to take BOTH the destination it was writing and the already-stageddiff --git a/server/services/fableLoom/editorial.js b/server/services/fableLoom/editorial.jsindex 869f3e270b..b33ab04ac9 100644--- a/server/services/fableLoom/editorial.js+++ b/server/services/fableLoom/editorial.js@@ -16,6 +16,7 @@ import {analyzeStoryOutline,analyzeStoryOutlineTeleplaySync,describeStoryOutlineForPrompt,+ fableLoomEpisodeChallenges,sanitizeStoryOutline,} from '../../lib/fableLoomOutline.js';import {@@ -222,6 +223,12 @@ const seriesPlanDigest = (loom) => JSON.stringify({})),}, null, 2);+const exactGraphIdContract = (episode) => asArray(episode.nodes).flatMap((node) => (+ asArray(node.transitions).map((transition) => (+ `transition=${transition.id} sourceNode=${node.id} targetNode=${transition.targetNodeId}`+ ))+)).join('\n');+const teleplayDigest = (loom) => asArray(loom.episodes).map((episode) => [`## Episode ${episode.number}: ${episode.title || 'Untitled'}`,`Episode id: ${episode.id}`,@@ -232,6 +239,9 @@ const teleplayDigest = (loom) => asArray(loom.episodes).map((episode) => [episode.nodes.length? describeGraphForPrompt(episode, { proseLimit: 1000, participationMode: loom.participationMode }): '(no expanded teleplay scenes)',+ episode.nodes.length+ ? `Exact graph ids for patches (copy verbatim):\n${exactGraphIdContract(episode) || '(no transitions)'}`+ : '',].filter(Boolean).join('\n')).join('\n\n');// Whole-record writes must conflict on every semantic persisted field. Only@@ -838,6 +848,7 @@ export function applyFableLoomEditorialPatch(const analysis = analyzeStoryOutline(storyOutline, {participationMode: candidate.participationMode,requireAudienceIntroduction: candidate.episodes[0]?.id === episode.id,+ challenges: fableLoomEpisodeChallenges(candidate, episode.id),});if (analysis.stats.errorCount) {throw aiShapeError(`The model returned an invalid outline for episode ${episode.id}: ${analysis.issues.find((issue) => issue.severity === 'error')?.message}`);@@ -1116,10 +1127,12 @@ export const __testing = {editorialPromptBudgetChars,editorialPromptCharacterCount,editorialFingerprint,+ exactGraphIdContract,finalizeEditorialOperation,loadEditorialDependencies,renderEditorialPrompt,sanitizeEvaluation,sanitizePlaythroughReview,+ teleplayDigest,withCompletePlaythroughDigest,};diff --git a/server/services/fableLoom/editorial.test.js b/server/services/fableLoom/editorial.test.jsindex 6a603a02c1..5a15d8e39e 100644--- a/server/services/fableLoom/editorial.test.js+++ b/server/services/fableLoom/editorial.test.js@@ -149,6 +149,16 @@ const completeOutline = () => ({],});+describe('editorial prompt graph contract', () => {+ it('gives the editor exact transition, source, and target ids for safe patches', () => {+ const digest = __testing.teleplayDigest(makeLoom());++ expect(digest).toContain('Exact graph ids for patches (copy verbatim):');+ expect(digest).toContain('transition=take-left sourceNode=opening targetNode=left');+ expect(digest).toContain('transition=right-end sourceNode=right targetNode=ending');+ });+});+describe('applyFableLoomEditorialPatch', () => {it('repairs a missing outline and selects a valid convergence source without changing membership', () => {const loom = makeLoom();diff --git a/server/services/fableLoom/editorialAutopilot.js b/server/services/fableLoom/editorialAutopilot.jsindex 124a79295e..b67bfe1ac3 100644--- a/server/services/fableLoom/editorialAutopilot.js+++ b/server/services/fableLoom/editorialAutopilot.js@@ -12,7 +12,7 @@ import { randomUUID } from 'node:crypto';import { ServerError } from '../../lib/errorHandler.js';import { LOOM_LIMITS } from '../../lib/fableLoomLimits.js';import { trimTo } from '../../lib/storyBible.js';-import { getLoom } from './records.js';+import { getLoom, mutateLoom } from './records.js';import {evaluateAndRemediateFableLoom,reviewFableLoomPlaythroughs,@@ -25,6 +25,7 @@ import {export const FABLELOOM_EDITORIAL_AUTOPILOT_LIMITS = Object.freeze({DEFAULT_ROUNDS: 3,MAX_ROUNDS: LOOM_LIMITS.EDITORIAL_AUTOPILOT_ROUNDS_MAX,+ MAX_RESPONSE_CORRECTIONS: 2,RUN_MAX_AGE_MS: 2 * 60 * 60 * 1000,MAX_CONCURRENT_RUNS: 10,});@@ -107,9 +108,57 @@ const routeOptions = (run) => ({...(run.route.effort ? { effort: run.route.effort } : {}),});+const responseCorrectionGuidance = (guidance, error, attempt) => trimTo([+ 'The previous editor response was rejected before any story changes were saved.',+ `Validator feedback: ${errorMessage(error)}`,+ `Correction attempt ${attempt} of ${FABLELOOM_EDITORIAL_AUTOPILOT_LIMITS.MAX_RESPONSE_CORRECTIONS}. Re-read the exact episode, scene, and transition ids in the teleplay digest. Return a corrected, graph-safe patch using only those ids; do not omit the original editorial work.`,+ guidance,+].filter(Boolean).join('\n\n'), 5000);++const invalidResponseExhaustedError = () => new ServerError(+ `Editorial autopilot could not obtain a graph-safe editor patch after ${FABLELOOM_EDITORIAL_AUTOPILOT_LIMITS.MAX_RESPONSE_CORRECTIONS + 1} attempts. Retry with a different model or repair the affected path manually, then restart autopilot.`,+ { status: 502, code: 'FABLELOOM_AUTOPILOT_INVALID_RESPONSE' },+);++const runRemediationStep = (+ run,+ round,+ baseGuidance,+ correctionAttempt = 0,+ attemptGuidance = baseGuidance,+) => (+ evaluateAndRemediateFableLoom(run.loomId, {+ ...routeOptions(run),+ guidance: attemptGuidance,+ }).catch((error) => {+ if (run.cancelRequested || error?.code !== 'AI_RESPONSE_INVALID') throw error;+ touch(run, { invalidResponses: (run.invalidResponses || 0) + 1 });+ if (correctionAttempt >= FABLELOOM_EDITORIAL_AUTOPILOT_LIMITS.MAX_RESPONSE_CORRECTIONS) {+ throw invalidResponseExhaustedError();+ }+ const nextCorrectionAttempt = correctionAttempt + 1;+ const nextEditorAttempt = nextCorrectionAttempt + 1;+ touch(run, {+ currentStep: 'response-correction',+ stepLabel: 'Correct editor response',+ correctionAttempt: nextCorrectionAttempt,+ responseCorrections: (run.responseCorrections || 0) + 1,+ message: `Step ${run.stepIndex} of up to ${run.stepCount} · round ${round}: correcting a rejected editor patch (attempt ${nextEditorAttempt} of ${FABLELOOM_EDITORIAL_AUTOPILOT_LIMITS.MAX_RESPONSE_CORRECTIONS + 1})…`,+ });+ return runRemediationStep(+ run,+ round,+ baseGuidance,+ nextCorrectionAttempt,+ responseCorrectionGuidance(baseGuidance, error, nextCorrectionAttempt),+ );+ })+);+const finishCanceled = (run, terminalFacts = {}) => touch(run, {status: 'canceled',currentStep: null,+ stepLabel: null,message: 'Editorial autopilot canceled after the active AI step finished.',completedAt: nowIso(),...terminalFacts,@@ -140,6 +189,7 @@ const finishPaused = async (run, pauseReason, message) => {status: 'paused',pauseReason,currentStep: null,+ stepLabel: null,message,selfImprove,completedAt: nowIso(),@@ -156,6 +206,7 @@ const finishFailed = async (run, error) => {return touch(run, {status: 'failed',currentStep: null,+ stepLabel: null,message: errorMessage(error),error: errorMessage(error),selfImprove,@@ -165,20 +216,25 @@ const finishFailed = async (run, error) => {async function runRound(run, guidance) {const round = run.round + 1;+ const remediationStep = ((round - 1) * 2) + 1;touch(run, {round,currentStep: 'evaluate-remediate',- message: `Round ${round}: evaluating and remediating the complete series…`,- });- const remediation = await evaluateAndRemediateFableLoom(run.loomId, {- ...routeOptions(run),- guidance,+ stepIndex: remediationStep,+ stepLabel: 'Evaluate and remediate',+ correctionAttempt: 0,+ message: `Step ${remediationStep} of up to ${run.stepCount} · round ${round}: evaluating and remediating the complete series…`,});+ const remediation = await runRemediationStep(run, round, guidance);if (run.cancelRequested) return finishCanceled(run);+ const reviewStep = remediationStep + 1;touch(run, {currentStep: 'playthrough-review',- message: `Round ${round}: exercising and reviewing branching playthroughs…`,+ stepIndex: reviewStep,+ stepLabel: 'Review every playthrough',+ correctionAttempt: 0,+ message: `Step ${reviewStep} of up to ${run.stepCount} · round ${round}: exercising and reviewing branching playthroughs…`,});const playtest = await reviewFableLoomPlaythroughs(run.loomId, {...routeOptions(run),@@ -207,11 +263,22 @@ async function runRound(run, guidance) {run.lastReview = playtest.review;if (playtest.passed) {+ const approvedAt = nowIso();+ await mutateLoom(run.loomId, (loom) => ({+ ...loom,+ productionStatus: {+ ...loom.productionStatus,+ editorialApprovedAt: approvedAt,+ editorialApprovalSource: 'autopilot',+ deliveryApprovedAt: null,+ },+ }));return touch(run, {status: 'completed',currentStep: null,+ stepLabel: null,message: `Editorial autopilot completed after ${round} round${round === 1 ? '' : 's'}.`,- completedAt: nowIso(),+ completedAt: approvedAt,});}@@ -266,6 +333,13 @@ export async function startFableLoomEditorialAutopilot(loomId, {currentStep: 'starting',round: 0,maxRounds: boundedRounds(maxRounds),+ stepIndex: 0,+ stepCount: boundedRounds(maxRounds) * 2,+ stepLabel: 'Starting',+ correctionAttempt: 0,+ responseCorrections: 0,+ invalidResponses: 0,+ maxResponseCorrections: FABLELOOM_EDITORIAL_AUTOPILOT_LIMITS.MAX_RESPONSE_CORRECTIONS,maxPaths: Number.isInteger(maxPaths) ? maxPaths : null,route: {providerId: providerId || null,@@ -297,6 +371,7 @@ export async function startFableLoomEditorialAutopilot(loomId, {touch(run, {status: 'failed',currentStep: null,+ stepLabel: null,message: errorMessage(error),error: errorMessage(error),completedAt: nowIso(),@@ -350,6 +425,7 @@ export const __testing = {compactDeterministic,findingSignature,guidanceFromFindings,+ responseCorrectionGuidance,residualFindings,runs,};diff --git a/server/services/fableLoom/editorialAutopilot.test.js b/server/services/fableLoom/editorialAutopilot.test.jsindex 7057b2bb95..34dc4e32f1 100644--- a/server/services/fableLoom/editorialAutopilot.test.js+++ b/server/services/fableLoom/editorialAutopilot.test.js@@ -1,6 +1,14 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const getLoomMock = vi.hoisted(() => vi.fn(async (id) => ({ id })));+const mutateLoomMock = vi.hoisted(() => vi.fn(async (id, mutator) => mutator({+ id,+ productionStatus: {+ editorialApprovedAt: null,+ editorialApprovalSource: null,+ deliveryApprovedAt: null,+ },+})));const remediateMock = vi.hoisted(() => vi.fn());const playtestMock = vi.hoisted(() => vi.fn());const selfImproveMock = vi.hoisted(() => vi.fn(async () => ({@@ -8,7 +16,7 @@ const selfImproveMock = vi.hoisted(() => vi.fn(async () => ({taskId: 'sys-example', filed: true, duplicate: false,})));-vi.mock('./records.js', () => ({ getLoom: getLoomMock }));+vi.mock('./records.js', () => ({ getLoom: getLoomMock, mutateLoom: mutateLoomMock }));vi.mock('./editorial.js', () => ({evaluateAndRemediateFableLoom: remediateMock,reviewFableLoomPlaythroughs: playtestMock,@@ -70,6 +78,7 @@ const waitForTerminal = async (runId) => {beforeEach(() => {_resetFableLoomEditorialAutopilots();getLoomMock.mockClear().mockImplementation(async (id) => ({ id }));+ mutateLoomMock.mockClear();remediateMock.mockReset();playtestMock.mockReset();selfImproveMock.mockClear();@@ -85,7 +94,9 @@ describe('FableLoom editorial autopilot', () => {});const finished = await waitForTerminal(started.id);- expect(finished).toMatchObject({ status: 'completed', round: 1, maxRounds: 3 });+ expect(finished).toMatchObject({+ status: 'completed', round: 1, maxRounds: 3, stepIndex: 2, stepCount: 6,+ });expect(finished.rounds).toHaveLength(1);expect(remediateMock).toHaveBeenCalledWith('loom-example', {providerId: 'writer', model: 'large', effort: 'high', guidance: '',@@ -94,6 +105,76 @@ describe('FableLoom editorial autopilot', () => {providerId: 'writer', model: 'large', effort: 'high', aiReview: true,});expect(selfImproveMock).not.toHaveBeenCalled();+ expect(mutateLoomMock).toHaveBeenCalledWith('loom-example', expect.any(Function));+ expect(await mutateLoomMock.mock.calls[0][1]({ productionStatus: {} })).toMatchObject({+ productionStatus: {+ editorialApprovedAt: expect.any(String),+ editorialApprovalSource: 'autopilot',+ deliveryApprovedAt: null,+ },+ });+ });++ it('corrects a rejected graph patch and continues the same editorial step', async () => {+ const rejectedPatch = Object.assign(new Error('The model returned an invalid transition target'), {+ code: 'AI_RESPONSE_INVALID',+ });+ remediateMock+ .mockRejectedValueOnce(rejectedPatch)+ .mockResolvedValueOnce(remediation(true));+ playtestMock.mockResolvedValueOnce(playtest({ passed: true }));++ const started = await startFableLoomEditorialAutopilot('loom-example', { maxRounds: 3 });+ const finished = await waitForTerminal(started.id);++ expect(finished).toMatchObject({+ status: 'completed', round: 1, stepIndex: 2, responseCorrections: 1, invalidResponses: 1,+ });+ expect(remediateMock).toHaveBeenCalledTimes(2);+ expect(remediateMock.mock.calls[1][1].guidance).toContain('Validator feedback');+ expect(remediateMock.mock.calls[1][1].guidance).toContain(rejectedPatch.message);+ expect(playtestMock).toHaveBeenCalledTimes(1);+ });++ it('feeds the newest validator rejection into each bounded correction attempt', async () => {+ const first = Object.assign(new Error('Unknown transition target in the opening scene'), {+ code: 'AI_RESPONSE_INVALID',+ });+ const second = Object.assign(new Error('Replacement ending still points at a removed scene'), {+ code: 'AI_RESPONSE_INVALID',+ });+ remediateMock+ .mockRejectedValueOnce(first)+ .mockRejectedValueOnce(second)+ .mockResolvedValueOnce(remediation(true));+ playtestMock.mockResolvedValueOnce(playtest({ passed: true }));++ const started = await startFableLoomEditorialAutopilot('loom-example', { maxRounds: 3 });+ const finished = await waitForTerminal(started.id);++ expect(finished).toMatchObject({+ status: 'completed', responseCorrections: 2, invalidResponses: 2,+ });+ expect(remediateMock.mock.calls[2][1].guidance).toContain(second.message);+ expect(remediateMock.mock.calls[2][1].guidance).not.toContain(first.message);+ });++ it('fails with useful remediation after exhausting invalid-response correction attempts', async () => {+ remediateMock.mockRejectedValue(Object.assign(+ new Error('The model returned an invalid transition target for a private record id'),+ { code: 'AI_RESPONSE_INVALID' },+ ));++ const started = await startFableLoomEditorialAutopilot('loom-example', { maxRounds: 3 });+ const finished = await waitForTerminal(started.id);++ expect(remediateMock).toHaveBeenCalledTimes(3);+ expect(finished).toMatchObject({+ status: 'failed', round: 1, stepIndex: 1, responseCorrections: 2, invalidResponses: 3,+ });+ expect(finished.error).toContain('graph-safe editor patch after 3 attempts');+ expect(finished.error).not.toContain('private record id');+ expect(playtestMock).not.toHaveBeenCalled();});it('pauses on a plateau after the same finding survives a no-change pass', async () => {@@ -143,9 +224,9 @@ describe('FableLoom editorial autopilot', () => {});});- it('keeps provider failures terminal while best-effort self-improvement diagnoses the failed step', async () => {+ it('keeps non-correctable provider failures terminal while best-effort self-improvement diagnoses the failed step', async () => {const providerError = Object.assign(new Error('Provider returned an unusable patch'), {- code: 'AI_RESPONSE_INVALID',+ code: 'PROVIDER_UNAVAILABLE',});remediateMock.mockRejectedValueOnce(providerError);@@ -161,7 +242,7 @@ describe('FableLoom editorial autopilot', () => {outcome: 'failed',reason: 'run-error',sourceStep: 'evaluate-remediate',- errorCode: 'AI_RESPONSE_INVALID',+ errorCode: 'PROVIDER_UNAVAILABLE',});});@@ -171,7 +252,7 @@ describe('FableLoom editorial autopilot', () => {finishDiagnosis = resolve;}));const providerError = Object.assign(new Error('Provider returned an unusable patch'), {- code: 'AI_RESPONSE_INVALID',+ code: 'PROVIDER_UNAVAILABLE',});remediateMock.mockRejectedValueOnce(providerError);diff --git a/server/services/fableLoom/production.js b/server/services/fableLoom/production.jsindex 1da46fbf16..21231d547d 100644--- a/server/services/fableLoom/production.js+++ b/server/services/fableLoom/production.js@@ -8,12 +8,13 @@* episode-level grouping, dependency barriers, cancellation, and resume UX.*/-import { randomUUID } from 'node:crypto';+import { randomInt, randomUUID } from 'node:crypto';import { basename } from 'node:path';import { ServerError } from '../../lib/errorHandler.js';import { resolveImageInputPath } from '../../lib/fileUtils.js';import { getImageModels, isEditOnly } from '../../lib/mediaModels.js';import { selectLocalImageModel, resolveLocalImageModel } from '../imageGen/prepareParams.js';+import { readImageSidecar } from '../imageGen/local.js';import {IMAGE_GEN_MODE,QUEUEABLE_IMAGE_MODES,@@ -28,6 +29,7 @@ import {listVideoModels,resolveVideoModel,} from '../videoGen/local.js';+import { loadHistory as loadVideoHistory } from '../videoGen/history.js';import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode } from '../videoGen/modes.js';import {compileFableLoomVisualRequest,@@ -36,7 +38,9 @@ import {} from './visualConditioning.js';import { cancelJob, enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';import {+ asFableLoomRenderSettings,buildEpisodeProductionPlan,+ exactRenderParameterIssues,FABLELOOM_PRODUCTION_MODE_DEFAULT,inspectEpisodeProductionOrder,} from '../../lib/fableLoomProduction.js';@@ -130,6 +134,121 @@ function normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel,};}+function renderGeometry(run, recordedConditioning = null) {+ const recorded = exactRenderParameters(run, recordedConditioning);+ return {+ width: Number.isFinite(recorded.width) ? recorded.width : run.render.width,+ height: Number.isFinite(recorded.height) ? recorded.height : run.render.height,+ aspectRatio: text(recorded.aspectRatio) || run.render.aspectRatio,+ };+}++function exactRenderParameters(run, recordedConditioning) {+ if (run.mode !== 'exact_inputs') return {};+ const issues = exactRenderParameterIssues(recordedConditioning);+ if (issues.length) {+ throw exactInputError(`Exact-input reproduction refused: ${issues.join(' ')}`);+ }+ return effectiveParameters(recordedConditioning.render.parameters);+}++const aspectMismatch = (width, height, expectedWidth, expectedHeight) => {+ if (![width, height, expectedWidth, expectedHeight].every((value) => Number.isFinite(value) && value > 0)) {+ return false;+ }+ const actual = width / height;+ const expected = expectedWidth / expectedHeight;+ return Math.abs(actual - expected) / expected > 0.02;+};++async function inspectImageDimensions(asset, node) {+ const filename = asset.existingAssetId;+ const { metadata } = await readImageSidecar(filename);+ if (Number.isFinite(Number(metadata?.width)) && Number.isFinite(Number(metadata?.height))) {+ return { width: Number(metadata.width), height: Number(metadata.height) };+ }+ const manifests = [+ node?.visualConditioning,+ ...Object.values(node?.playbackAssets?.visualConditioningByAsset || {}),+ ];+ const recorded = manifests.find((manifest) => manifest?.capability?.kind === 'image'+ && manifest?.assetId === asset.id)?.render?.parameters;+ return Number.isFinite(recorded?.width) && Number.isFinite(recorded?.height)+ ? { width: recorded.width, height: recorded.height }+ : null;+}++function inspectVideoDimensions(asset, node, historyById) {+ const history = historyById.get(asset.existingAssetId);+ if (Number.isFinite(Number(history?.width)) && Number.isFinite(Number(history?.height))) {+ return { width: Number(history.width), height: Number(history.height) };+ }+ const perAsset = node?.playbackAssets?.visualConditioningByAsset || {};+ const recorded = (perAsset[asset.existingAssetId]+ || perAsset[asset.id]+ || Object.values(perAsset).find((manifest) => manifest?.assetId === asset.id))+ ?.render?.parameters;+ return Number.isFinite(recorded?.width) && Number.isFinite(recorded?.height)+ ? { width: recorded.width, height: recorded.height }+ : null;+}++async function flagRenderFormatMismatches(plan, episode, render) {+ plan.formatMismatches = [];+ if (plan.mode === 'exact_inputs') return plan;+ const nodeById = new Map((episode.nodes || []).map((node) => [node.id, node]));+ const existingAssets = plan.plannedAssets.filter((asset) => asset.existingAssetId+ && (asset.type === 'image' || asset.type.startsWith('video_')));+ const videoAssets = existingAssets.filter((asset) => asset.type.startsWith('video_'));+ const history = videoAssets.length ? await loadVideoHistory() : [];+ const historyById = new Map((Array.isArray(history) ? history : [])+ .filter((item) => item?.id)+ .map((item) => [item.id, item]));+ const inspected = await Promise.all(existingAssets.map(async (asset) => ({+ asset,+ dimensions: asset.type === 'image'+ ? await inspectImageDimensions(asset, nodeById.get(asset.nodeId))+ : inspectVideoDimensions(asset, nodeById.get(asset.nodeId), historyById),+ })));+ const formatMismatches = [];+ const forcedAssetIds = new Set();+ for (const { asset, dimensions } of inspected) {+ if (forcedAssetIds.has(asset.id)) continue;+ if (!dimensions || !aspectMismatch(dimensions.width, dimensions.height, render.width, render.height)) continue;+ const mismatch = {+ assetId: asset.id,+ assetType: asset.type,+ nodeId: asset.nodeId,+ nodeTitle: asset.nodeTitle,+ actualWidth: dimensions.width,+ actualHeight: dimensions.height,+ expectedWidth: render.width,+ expectedHeight: render.height,+ expectedAspectRatio: render.aspectRatio,+ };+ formatMismatches.push(mismatch);+ const relatedAssets = asset.type === 'image'+ ? plan.plannedAssets.filter((candidate) => candidate.nodeId === asset.nodeId+ && (candidate.type === 'image' || candidate.type.startsWith('video_'))+ && candidate.existingAssetId)+ : [asset];+ for (const related of relatedAssets) {+ related.formatMismatch = mismatch;+ if (related.readiness?.ready !== false) related.status = 'ready';+ forcedAssetIds.add(related.id);+ }+ }+ plan.formatMismatches = formatMismatches;+ plan.readyAssetsCount = plan.plannedAssets.filter((asset) => asset.status === 'ready').length;+ plan.alreadyRenderedCount = plan.plannedAssets.filter((asset) => asset.status === 'already_rendered').length;+ plan.skippedAssetsCount = plan.plannedAssets.filter((asset) => asset.status === 'skipped').length;+ plan.blockedAssetsCount = plan.plannedAssets.filter((asset) => asset.status === 'blocked').length;+ plan.isFullyReady = plan.blockedAssetsCount === 0+ && plan.exactInputIssues.length === 0+ && plan.planningIssues.length === 0;+ return plan;+}+function selectAssets(plan, { assetTypes = null, nodeIds = null } = {}) {const typeFilter = Array.isArray(assetTypes) && assetTypes.length > 0 ? new Set(assetTypes) : null;const nodeFilter = Array.isArray(nodeIds) && nodeIds.length > 0 ? new Set(nodeIds) : null;@@ -174,6 +293,7 @@ function assetState(asset) {existingAssetId: asset.existingAssetId || null,readiness: asset.readiness || { ready: false, reasons: [] },skipReason: asset.skipReason || null,+ formatMismatch: asset.formatMismatch || null,status: alreadyRendered ? 'completed' : skipped ? 'skipped' : 'pending',jobId: null,provider: null,@@ -376,6 +496,8 @@ async function prepareImageJob(run, asset) {if (run.mode === 'exact_inputs') assertExactConditioning(recordedConditioning, conditioned?.visualConditioning);const referenceImagePaths = conditioned?.referenceImagePaths || [];const localInitImagePath = conditioned?.sourceImagePath || referenceImagePaths[0] || null;+ const geometry = renderGeometry(run, recordedConditioning);+ const replayParameters = exactRenderParameters(run, recordedConditioning);if (mode === IMAGE_GEN_MODE.LOCAL) {const local = resolveLocalImageModel(settings, {@@ -399,11 +521,14 @@ async function prepareImageJob(run, asset) {prompt: conditioned?.prompt || asset.prompt,negativePrompt: conditioned?.negativePrompt || '',modelId: local.selectedModel.id,- width: 1024,- height: 1024,- steps: settings.imageGen?.local?.steps,- guidance: settings.imageGen?.local?.guidance,+ width: geometry.width,+ height: geometry.height,+ aspectRatio: geometry.aspectRatio,+ steps: settings.imageGen?.local?.steps ?? local.selectedModel.steps,+ guidance: settings.imageGen?.local?.guidance ?? local.selectedModel.guidance,quantize: settings.imageGen?.local?.quantize ?? '8',+ seed: randomInt(0, 2_147_483_647),+ ...replayParameters,...(selectedIsEditOnly && localInitImagePath ? { initImagePath: localInitImagePath } : {}),referenceImagePaths: selectedIsEditOnly ? referenceImagePaths.slice(1) : referenceImagePaths,referenceImageStrengths: selectedIsEditOnly@@ -437,8 +562,10 @@ async function prepareImageJob(run, asset) {...providerParams,prompt: conditioned?.prompt || asset.prompt,negativePrompt: conditioned?.negativePrompt || '',- width: 1024,- height: 1024,+ width: geometry.width,+ height: geometry.height,+ aspectRatio: geometry.aspectRatio,+ ...replayParameters,initImagePath: conditioned?.sourceImagePath || null,referenceImagePaths,referenceImageStrengths: conditioned?.referenceImageStrengths || [],@@ -475,6 +602,8 @@ async function prepareVideoJob(run, asset) {const conditioned = await conditionRequest(run, asset, 'video', capability, requestedSourceImagePath);if (run.mode === 'exact_inputs') assertExactConditioning(recordedConditioning, conditioned?.visualConditioning);const sourceImagePath = conditioned ? conditioned.sourceImagePath : requestedSourceImagePath;+ const geometry = renderGeometry(run, recordedConditioning);+ const replayParameters = exactRenderParameters(run, recordedConditioning);if (backend === VIDEO_GEN_MODE.LOCAL) {const supportedModes = Array.isArray(model.supportedModes) ? model.supportedModes : [];@@ -495,14 +624,19 @@ async function prepareVideoJob(run, asset) {prompt: conditioned?.prompt || asset.prompt,negativePrompt: conditioned?.negativePrompt || '',modelId: model.id,- width: model.defaultWidth || 1024,- height: model.defaultHeight || 576,+ width: geometry.width,+ height: geometry.height,+ aspectRatio: geometry.aspectRatio,numFrames: model.defaultFrames || DEFAULT_NUM_FRAMES,- fps: model.defaultFps || 24,- steps: model.defaultSteps,- guidanceScale: model.defaultGuidanceScale,+ fps: model.defaultFps || model.fpsOptions?.[0] || 24,+ steps: model.steps,+ guidanceScale: model.guidance,+ seed: randomInt(0, 2_147_483_647),+ tiling: 'auto',+ disableAudio: false,sourceImagePath,mode: videoMode,+ ...replayParameters,visualConditioning: conditioned?.visualConditioning || null,fableLoom: productionTag(run, asset),},@@ -530,8 +664,10 @@ async function prepareVideoJob(run, asset) {...cloud.providerParams,prompt: conditioned?.prompt || asset.prompt,negativePrompt: conditioned?.negativePrompt || '',- width: 1024,- height: 576,+ width: geometry.width,+ height: geometry.height,+ aspectRatio: geometry.aspectRatio,+ ...replayParameters,sourceImagePath,visualConditioning: conditioned?.visualConditioning || null,fableLoom: productionTag(run, asset),@@ -730,6 +866,11 @@ export async function planEpisodeProduction(loomId, episodeId, {availableVideoModels: listVideoModels(),resolveAsset: resolveImageInputPath,});+ const render = {+ ...normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel, effort }),+ ...asFableLoomRenderSettings(loom.renderSettings),+ };+ await flagRenderFormatMismatches(plan, episode, render);const episodeOrderReadiness = inspectEpisodeProductionOrder(loom, episode);plan.episodeOrderReadiness = episodeOrderReadiness;if (!episodeOrderReadiness.ready) {@@ -740,7 +881,6 @@ export async function planEpisodeProduction(loomId, episodeId, {for (const issue of seriesStoryReadiness.issues.filter((candidate) => candidate.severity === 'error')) {plan.planningIssues.push(`Story arc: ${issue.message}`);}- const render = normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel, effort });const settings = await getSettings();if (plan.mode === 'exact_inputs') {const exactEnvironmentIssues = new Set();@@ -799,6 +939,9 @@ export async function planEpisodeProduction(loomId, episodeId, {plan.planningIssues.push(`Video model "${videoModelId}" is not available on this machine.`);}}+ plan.isFullyReady = plan.blockedAssetsCount === 0+ && plan.exactInputIssues.length === 0+ && plan.planningIssues.length === 0;return {...plan,renderOptions: render,@@ -825,8 +968,9 @@ export async function startEpisodeProductionBatch(loomId, episodeId, {});}- const render = normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel, effort });- const plan = await planEpisodeProduction(loomId, episodeId, { mode, ...render });+ const requestedRender = normalizedRenderOptions({ imageMode, imageModel, videoMode, videoModel, effort });+ const plan = await planEpisodeProduction(loomId, episodeId, { mode, ...requestedRender });+ const render = plan.renderOptions;const targetAssets = selectAssets(plan, { assetTypes, nodeIds });const blockedAssets = targetAssets.filter((asset) => asset.status === 'blocked');if (blockedAssets.length > 0 || plan.exactInputIssues.length > 0 || plan.planningIssues.length > 0) {diff --git a/server/services/fableLoom/production.test.js b/server/services/fableLoom/production.test.jsindex 653ca05584..bef8bac341 100644--- a/server/services/fableLoom/production.test.js+++ b/server/services/fableLoom/production.test.js@@ -36,12 +36,16 @@ const imagePrepareMocks = vi.hoisted(() => ({selectLocalImageModel: vi.fn(),resolveLocalImageModel: vi.fn(),}));+const imageSidecarMocks = vi.hoisted(() => ({+ readImageSidecar: vi.fn(async () => ({ metadata: {} })),+}));const videoModelMocks = vi.hoisted(() => ({DEFAULT_NUM_FRAMES: 16,defaultVideoModelId: vi.fn(),listVideoModels: vi.fn(),resolveVideoModel: vi.fn(),}));+const videoHistoryMocks = vi.hoisted(() => ({ loadHistory: vi.fn() }));const visualConditioningMocks = vi.hoisted(() => ({compileFableLoomVisualRequest: vi.fn(),fableLoomImageCapabilities: vi.fn(),@@ -55,7 +59,9 @@ vi.mock('../loras.js');vi.mock('../settings.js', () => settingsMocks);vi.mock('../../lib/mediaModels.js', () => mediaModelMocks);vi.mock('../imageGen/prepareParams.js', () => imagePrepareMocks);+vi.mock('../imageGen/local.js', () => imageSidecarMocks);vi.mock('../videoGen/local.js', () => videoModelMocks);+vi.mock('../videoGen/history.js', () => videoHistoryMocks);vi.mock('../mediaJobQueue/index.js', () => queueMocks);vi.mock('./visualConditioning.js', () => visualConditioningMocks);@@ -133,7 +139,10 @@ describe('fableLoom production service', () => {voiceProfiles.listVoiceProfiles.mockResolvedValue([]);loras.listLoras.mockResolvedValue([]);settingsMocks.getSettings.mockResolvedValue({ imageGen: { local: {} }, videoGen: {} });- const imageModel = { id: 'image-model', runner: 'flux2', hardwareCompatibility: { state: 'ready', reasons: [] } };+ const imageModel = {+ id: 'image-model', revision: 'image-revision-1', runner: 'flux2',+ hardwareCompatibility: { state: 'ready', reasons: [] },+ };mediaModelMocks.getImageModels.mockReturnValue([imageModel]);mediaModelMocks.isEditOnly.mockReturnValue(false);imagePrepareMocks.selectLocalImageModel.mockReturnValue(imageModel);@@ -145,9 +154,14 @@ describe('fableLoom production service', () => {defaultWidth: 1024,defaultHeight: 576,defaultFrames: 16,+ defaultFps: 24,+ steps: 30,+ guidance: 4,+ revision: 'video-revision-1',};videoModelMocks.listVideoModels.mockReturnValue([videoModel]);videoModelMocks.resolveVideoModel.mockReturnValue(videoModel);+ videoHistoryMocks.loadHistory.mockResolvedValue([]);visualConditioningMocks.compileFableLoomVisualRequest.mockResolvedValue(null);visualConditioningMocks.fableLoomImageCapabilities.mockReturnValue({kind: 'image', backend: 'local', modelId: 'image-model', referenceRoles: [], referenceBudget: 0,@@ -155,6 +169,8 @@ describe('fableLoom production service', () => {visualConditioningMocks.fableLoomVideoCapabilities.mockReturnValue({kind: 'video', backend: 'local', modelId: 'video-model', referenceRoles: [], referenceBudget: 0,});+ imageSidecarMocks.readImageSidecar.mockReset();+ imageSidecarMocks.readImageSidecar.mockResolvedValue({ metadata: {} });let nextJobId = 1;queueMocks.enqueueJob.mockImplementation(() => ({ jobId: `job-${nextJobId++}`, position: 1, status: 'queued' }));queueMocks.cancelJob.mockResolvedValue({ ok: true, status: 'canceled' });@@ -168,6 +184,60 @@ describe('fableLoom production service', () => {expect(plan.plannedAssets.some((a) => a.id === 'asset-node-1-still')).toBe(true);expect(plan.plannedAssets.some((a) => a.id === 'asset-node-2-still')).toBe(true);expect(plan.seriesStoryReadiness.stats.ready).toBe(true);+ expect(plan.renderOptions).toMatchObject({+ formatId: 'landscape-16-9', aspectRatio: '16:9', width: 1024, height: 576,+ });+ });++ it('flags an existing portrait storyboard and its clips for landscape regeneration', async () => {+ const portraitLoom = structuredClone(sampleLoom);+ portraitLoom.episodes[0].nodes[0].image = 'portrait.png';+ portraitLoom.episodes[0].nodes[0].videoHistoryId = 'portrait-video';+ records.getLoom.mockResolvedValueOnce(portraitLoom);+ imageSidecarMocks.readImageSidecar.mockResolvedValueOnce({+ metadata: { width: 576, height: 1024 },+ });++ const plan = await planEpisodeProduction('loom-1', 'ep-1', { mode: 'current_canon' });++ expect(plan.formatMismatches).toEqual([expect.objectContaining({+ nodeId: 'node-1',+ actualWidth: 576,+ actualHeight: 1024,+ expectedAspectRatio: '16:9',+ })]);+ expect(plan.plannedAssets.find((asset) => asset.id === 'asset-node-1-still')).toMatchObject({+ status: 'ready',+ formatMismatch: expect.objectContaining({ expectedWidth: 1024, expectedHeight: 576 }),+ });+ expect(plan.plannedAssets.find((asset) => asset.id === 'asset-node-1-video-entry')).toMatchObject({+ status: 'ready',+ formatMismatch: expect.objectContaining({ expectedAspectRatio: '16:9' }),+ });+ });++ it('inspects existing video dimensions even when the storyboard already matches', async () => {+ const portraitVideoLoom = structuredClone(sampleLoom);+ portraitVideoLoom.episodes[0].nodes[0].image = 'landscape.png';+ portraitVideoLoom.episodes[0].nodes[0].videoHistoryId = 'portrait-video';+ records.getLoom.mockResolvedValueOnce(portraitVideoLoom);+ imageSidecarMocks.readImageSidecar.mockResolvedValueOnce({+ metadata: { width: 1024, height: 576 },+ });+ videoHistoryMocks.loadHistory.mockResolvedValueOnce([{+ id: 'portrait-video', width: 576, height: 1024,+ }]);++ const plan = await planEpisodeProduction('loom-1', 'ep-1', { mode: 'current_canon' });++ expect(plan.formatMismatches).toEqual([expect.objectContaining({+ assetId: 'asset-node-1-video-entry',+ assetType: 'video_entry',+ actualWidth: 576,+ actualHeight: 1024,+ })]);+ expect(plan.plannedAssets.find((asset) => asset.id === 'asset-node-1-video-entry'))+ .toMatchObject({ status: 'ready', formatMismatch: expect.any(Object) });});it('blocks production planning until the complete series beat arc is validated', async () => {@@ -209,6 +279,12 @@ describe('fableLoom production service', () => {expect(run.plan.executionStages.length).toBeGreaterThan(0);expect(run.assets[0]).toHaveProperty('dependencies');+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(queueMocks.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'image',+ params: expect.objectContaining({ width: 1024, height: 576, aspectRatio: '16:9' }),+ }));+const fetched = getEpisodeProductionBatch(run.id);expect(fetched).toEqual(run);});@@ -229,6 +305,69 @@ describe('fableLoom production service', () => {.rejects.toMatchObject({ code: 'EXACT_INPUTS_REFUSED', status: 409 });});+ it('replays the complete recorded image parameter tuple in exact-input mode', async () => {+ const exactLoom = structuredClone(sampleLoom);+ const recorded = (assetId) => ({+ version: 1,+ compilerVersion: 'visual-v1',+ status: 'locked',+ universeId: 'univ-1',+ assetId,+ capability: {+ kind: 'image', backend: 'local', modelId: 'image-model', modelRevision: 'image-revision-1',+ },+ bindings: { inferred: false, characterAppearances: [], objectIds: [] },+ assets: [],+ adapters: [],+ omitted: [],+ warnings: [],+ render: {+ parameters: {+ width: 1280,+ height: 720,+ aspectRatio: '16:9',+ steps: 41,+ guidance: 5.25,+ quantize: '4',+ seed: 987654,+ },+ },+ });+ for (const node of exactLoom.episodes[0].nodes) {+ node.image = `${node.id}.png`;+ node.visualConditioning = recorded(`asset-${node.id}-still`);+ }+ records.getLoom.mockResolvedValue(exactLoom);+ visualConditioningMocks.compileFableLoomVisualRequest.mockImplementation(async ({ tag }) => ({+ prompt: 'Recorded prompt',+ negativePrompt: '',+ referenceImagePaths: [],+ referenceImageStrengths: [],+ loraFilenames: [],+ loraScales: [],+ visualConditioning: recorded(`asset-${tag.nodeId}-still`),+ }));++ await startEpisodeProductionBatch('loom-1', 'ep-1', {+ mode: 'exact_inputs',+ assetTypes: ['image'],+ });+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(queueMocks.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'image',+ params: expect.objectContaining({+ width: 1280,+ height: 720,+ aspectRatio: '16:9',+ steps: 41,+ guidance: 5.25,+ quantize: '4',+ seed: 987654,+ }),+ }));+ });+it('cancels an in-progress batch run', async () => {const run = await startEpisodeProductionBatch('loom-1', 'ep-1', { mode: 'current_canon' });const canceled = await cancelEpisodeProductionBatch(run.id);diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.jsindex ec947d5240..6902706f81 100644--- a/server/services/fableLoom/records.js+++ b/server/services/fableLoom/records.js@@ -57,9 +57,14 @@ import {} from '../../lib/fableLoomParticipation.js';import { normalizeFableLoomCameraMovement } from '../../lib/fableLoomCameraMovements.js';import {+ analyzeStoryOutline,analyzeStoryOutlineTeleplaySync,+ FABLELOOM_CHALLENGE_PHASES,+ fableLoomEpisodeChallenges,+ fableLoomPlotPointKind,sanitizeStoryOutline,} from '../../lib/fableLoomOutline.js';+import { asFableLoomRenderSettings } from '../../lib/fableLoomProduction.js';export { LOOM_LIMITS };@@ -119,6 +124,12 @@ function sanitizeNode(raw) {id: raw.id,title: trimTo(raw.title, LOOM_LIMITS.NODE_TITLE_MAX),prose: trimTo(raw.prose, LOOM_LIMITS.PROSE_MAX),+ plotPointId: isStr(raw.plotPointId)+ ? raw.plotPointId.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)+ : null,+ challengePhase: FABLELOOM_CHALLENGE_PHASES.includes(raw.challengePhase)+ ? raw.challengePhase+ : null,imagePrompt: trimTo(raw.imagePrompt, LOOM_LIMITS.IMAGE_PROMPT_MAX),image: isSafeImageFilename(raw.image) ? raw.image : null,imageJobId: isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId.slice(0, 200) : null,@@ -225,6 +236,7 @@ function sanitizeSeriesPlan(raw, episodes) {.slice(0, LOOM_LIMITS.PLAN_ITEMS_MAX).map((item) => ({id: planItemId('plot', item.id, plotIds),+ kind: fableLoomPlotPointKind(item),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),@@ -261,8 +273,18 @@ export function sanitizeLoom(raw) {.filter(Boolean).slice(0, LOOM_LIMITS.EPISODES_MAX).sort((a, b) => a.number - b.number || a.createdAt.localeCompare(b.createdAt));+ const seriesPlan = sanitizeSeriesPlan(raw.seriesPlan, episodes);for (const episode of episodes) {if (episode.storyOutline?.validation?.status !== 'valid') continue;+ const outline = analyzeStoryOutline(episode.storyOutline, {+ participationMode,+ requireAudienceIntroduction: episode === episodes[0],+ challenges: fableLoomEpisodeChallenges({ seriesPlan }, episode.id),+ });+ if (outline.stats.errorCount > 0) {+ episode.storyOutline.validation = { status: 'invalid', issues: outline.issues };+ continue;+ }const sync = analyzeStoryOutlineTeleplaySync(episode, episode.storyOutline, {participationMode,});@@ -272,9 +294,26 @@ export function sanitizeLoom(raw) {}const protagonistCharacterId = nullableRef(raw.protagonistCharacterId);const protagonistWardrobeId = nullableRef(raw.protagonistWardrobeId);+ const productionStatus = raw.productionStatus && typeof raw.productionStatus === 'object'+ ? {+ editorialApprovedAt: isStr(raw.productionStatus.editorialApprovedAt)+ ? raw.productionStatus.editorialApprovedAt.slice(0, 80)+ : null,+ editorialApprovalSource: ['manual', 'autopilot'].includes(raw.productionStatus.editorialApprovalSource)+ ? raw.productionStatus.editorialApprovalSource+ : null,+ deliveryApprovedAt: isStr(raw.productionStatus.deliveryApprovedAt)+ ? raw.productionStatus.deliveryApprovedAt.slice(0, 80)+ : null,+ }+ : {+ editorialApprovedAt: null,+ editorialApprovalSource: null,+ deliveryApprovedAt: null,+ };return {id: raw.id,- schemaVersion: 2,+ schemaVersion: 3,name,logline: trimTo(raw.logline, LOOM_LIMITS.LOGLINE_MAX),premise: trimTo(raw.premise, LOOM_LIMITS.PREMISE_MAX),@@ -289,12 +328,14 @@ export function sanitizeLoom(raw) {// turns a reader's free text into a path. An unset dimension stays null// ('fall through to the stage pin / active provider').playSettings: sanitizeLlmRoutePin(raw.playSettings),+ renderSettings: asFableLoomRenderSettings(raw.renderSettings),protagonistCharacterId,protagonistWardrobeId,protagonistWardrobeLocked: Boolean(protagonistWardrobeId && raw.protagonistWardrobeLocked !== false),universeId: nullableRef(raw.universeId),seriesId: nullableRef(raw.seriesId),- seriesPlan: sanitizeSeriesPlan(raw.seriesPlan, episodes),+ seriesPlan,+ productionStatus,episodes,createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : now,updatedAt: isStr(raw.updatedAt) && raw.updatedAt ? raw.updatedAt : now,@@ -303,6 +344,78 @@ export function sanitizeLoom(raw) {};}+const editorialVisualCanon = (visualCanon) => {+ if (!visualCanon) return null;+ const { storyboardImageApproved: _storyboardImageApproved, ...storyCanon } = visualCanon;+ return storyCanon;+};++// Approval invalidation is content-aware: authoring edits reopen editorial and+// final delivery, while a completed render only reopens delivery. This avoids+// using loom.updatedAt as a proxy, because media completion also updates it.+const editorialContentSignature = (loom) => JSON.stringify({+ name: loom.name,+ logline: loom.logline,+ premise: loom.premise,+ styleNotes: loom.styleNotes,+ participationMode: loom.participationMode,+ audienceCommunicationMedium: loom.audienceCommunicationMedium,+ format: loom.format,+ protagonistCharacterId: loom.protagonistCharacterId,+ protagonistWardrobeId: loom.protagonistWardrobeId,+ protagonistWardrobeLocked: loom.protagonistWardrobeLocked,+ universeId: loom.universeId,+ seriesId: loom.seriesId,+ seriesPlan: loom.seriesPlan,+ episodes: loom.episodes.map((episode) => ({+ id: episode.id,+ number: episode.number,+ title: episode.title,+ synopsis: episode.synopsis,+ startNodeId: episode.startNodeId,+ storyOutline: episode.storyOutline ? {+ version: episode.storyOutline.version,+ startKey: episode.storyOutline.startKey,+ scenes: episode.storyOutline.scenes,+ } : null,+ nodes: episode.nodes.map((node) => ({+ id: node.id,+ title: node.title,+ prose: node.prose,+ plotPointId: node.plotPointId,+ challengePhase: node.challengePhase,+ imagePrompt: node.imagePrompt,+ videoPrompt: node.videoPrompt,+ cameraMovement: node.cameraMovement,+ visualCanon: editorialVisualCanon(node.visualCanon),+ playbackMode: node.playbackMode,+ audienceConnection: node.audienceConnection,+ protagonistPresence: node.protagonistPresence,+ interactionWindow: node.interactionWindow,+ isEnding: node.isEnding,+ format: node.format,+ endingLabel: node.endingLabel,+ transitions: node.transitions,+ })),+ })),+});++const deliveryContentSignature = (loom) => JSON.stringify({+ renderSettings: loom.renderSettings,+ episodes: loom.episodes.map((episode) => ({+ id: episode.id,+ nodes: episode.nodes.map((node) => ({+ id: node.id,+ image: node.image,+ imageJobId: node.imageJobId,+ videoHistoryId: node.videoHistoryId,+ playbackAssets: node.playbackAssets,+ visualConditioning: node.visualConditioning,+ storyboardImageApproved: node.visualCanon?.storyboardImageApproved === true,+ })),+ })),+});+const notFound = (what = 'Loom') => new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' });// Soft refs are validated at write time (against the trimmed value that will@@ -385,7 +498,7 @@ const assertParticipationConfigured = ({ participationMode, audienceCommunicatio};export async function createLoom({- name, logline, premise, styleNotes, format, playSettings, seriesPlan,+ name, logline, premise, styleNotes, format, playSettings, renderSettings, seriesPlan,protagonistCharacterId, protagonistWardrobeId, protagonistWardrobeLocked,participationMode = FABLELOOM_LEGACY_PARTICIPATION_MODE,audienceCommunicationMedium, universeId, seriesId,@@ -403,6 +516,7 @@ export async function createLoom({audienceCommunicationMedium,format,playSettings,+ renderSettings,protagonistCharacterId,protagonistWardrobeId,protagonistWardrobeLocked,@@ -429,10 +543,21 @@ export async function mutateLoom(id, mutator) {if (!isValidLoomId(id)) throw notFound();const result = await queueLoomWrite(id, async () => {const current = await requireLoomRaw(id);+ const currentEditorialSignature = editorialContentSignature(current);+ const currentDeliverySignature = deliveryContentSignature(current);const changed = await mutator(current);if (!changed) return { loom: current, changed: false };const next = sanitizeLoom({ ...changed, id, updatedAt: new Date().toISOString() });if (!next) throw new ServerError('Invalid loom record', { status: 400, code: 'VALIDATION_ERROR' });+ const editorialChanged = editorialContentSignature(next) !== currentEditorialSignature;+ const deliveryChanged = deliveryContentSignature(next) !== currentDeliverySignature;+ if (editorialChanged) {+ next.productionStatus.editorialApprovedAt = null;+ next.productionStatus.editorialApprovalSource = null;+ next.productionStatus.deliveryApprovedAt = null;+ } else if (deliveryChanged) {+ next.productionStatus.deliveryApprovedAt = null;+ }await writeRaw(id, next);return { loom: next, changed: true };});@@ -441,13 +566,15 @@ export async function mutateLoom(id, mutator) {}const PATCH_FIELDS = [- 'name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan',+ 'name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'renderSettings', 'seriesPlan',+ 'productionStatus','protagonistCharacterId', 'protagonistWardrobeId', 'protagonistWardrobeLocked','participationMode', 'audienceCommunicationMedium', 'universeId', 'seriesId',];const RESTORABLE_FIELDS = [- 'name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan',+ 'name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'renderSettings', 'seriesPlan',+ 'productionStatus','protagonistCharacterId', 'protagonistWardrobeId', 'protagonistWardrobeLocked','participationMode', 'audienceCommunicationMedium', 'episodes',];@@ -500,23 +627,54 @@ export async function deleteLoom(id) {// them. A sender at the current schema version's present null remains an// intentional clear.const preserveLegacyVisualProduction = (remote, local, senderVersion) => {- if (!local || senderVersion >= 4) return remote;+ if (!local || senderVersion >= 5) return remote;const localEpisodes = new Map(local.episodes.map((episode) => [episode.id, episode]));+ const localPlotPoints = new Map((local.seriesPlan?.plotPoints || []).map((item) => [item.id, item]));return {...remote,+ ...(senderVersion < 5 ? {+ renderSettings: local.renderSettings,+ productionStatus: local.productionStatus,+ } : {}),+ seriesPlan: senderVersion < 5 ? {+ ...remote.seriesPlan,+ plotPoints: (remote.seriesPlan?.plotPoints || []).map((item) => ({+ ...item,+ ...(localPlotPoints.has(item.id) ? { kind: localPlotPoints.get(item.id).kind } : {}),+ })),+ } : remote.seriesPlan,...(senderVersion < 4 ? {protagonistCharacterId: local.protagonistCharacterId,protagonistWardrobeId: local.protagonistWardrobeId,protagonistWardrobeLocked: local.protagonistWardrobeLocked,} : {}),episodes: remote.episodes.map((episode) => {- const localNodes = new Map((localEpisodes.get(episode.id)?.nodes || []).map((node) => [node.id, node]));+ const localEpisode = localEpisodes.get(episode.id);+ const localNodes = new Map((localEpisode?.nodes || []).map((node) => [node.id, node]));+ const localOutlineScenes = new Map((localEpisode?.storyOutline?.scenes || [])+ .map((scene) => [scene.key, scene]));return {...episode,+ ...(senderVersion < 5 && episode.storyOutline ? {+ storyOutline: {+ ...episode.storyOutline,+ scenes: episode.storyOutline.scenes.map((scene) => ({+ ...scene,+ ...(localOutlineScenes.has(scene.key) ? {+ plotPointId: localOutlineScenes.get(scene.key).plotPointId,+ challengePhase: localOutlineScenes.get(scene.key).challengePhase,+ } : {}),+ })),+ },+ } : {}),nodes: episode.nodes.map((node) => {const localNode = localNodes.get(node.id);return localNode ? {...node,+ ...(senderVersion < 5 ? {+ plotPointId: localNode.plotPointId,+ challengePhase: localNode.challengePhase,+ } : {}),...(senderVersion < 4 ? { protagonistPresence: localNode.protagonistPresence } : {}),...(senderVersion < 3 ? {visualCanon: localNode.visualCanon,@@ -544,7 +702,7 @@ export async function mergeLoomsFromSync(remoteLooms,{source = { via: 'sync', peerId: null },- senderSchemaVersions = { fableLoom: 4 },+ senderSchemaVersions = { fableLoom: 5 },} = {},) {if (!Array.isArray(remoteLooms)) return { applied: false, count: 0 };@@ -681,7 +839,7 @@ export function deleteEpisode(loomId, episodeId) {// --- Nodes & transitions ----------------------------------------------------const NODE_PATCH_FIELDS = [- 'title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode',+ 'title', 'prose', 'plotPointId', 'challengePhase', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode','audienceConnection', 'protagonistPresence', 'visualCanon', 'videoHistoryId', 'playbackAssets', 'interactionWindow','isEnding', 'endingLabel', 'pos', 'transitions',];@@ -817,6 +975,18 @@ export async function attachNodeImage(loomId, episodeId, nodeId, { filename, jobnode.image = filename;node.imageJobId = isStr(jobId) ? jobId : null;node.visualConditioning = visualConditioning;+ const retainedConditioning = Object.fromEntries(Object.entries(+ node.playbackAssets?.visualConditioningByAsset || {},+ ).filter(([, manifest]) => manifest?.capability?.kind !== 'image'));+ if (node.playbackAssets) {+ node.playbackAssets = {+ ...node.playbackAssets,+ ...(Object.keys(retainedConditioning).length+ ? { visualConditioningByAsset: retainedConditioning }+ : {}),+ };+ if (!Object.keys(retainedConditioning).length) delete node.playbackAssets.visualConditioningByAsset;+ }if (visualConditioning && isSafeVideoHistoryId(visualConditioning.assetId)) {node.playbackAssets = {...(node.playbackAssets || {}),diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.jsindex f2ddd58ada..5b7666cf0b 100644--- a/server/services/fableLoom/records.test.js+++ b/server/services/fableLoom/records.test.js@@ -363,6 +363,102 @@ describe('loom CRUD', () => {expect(merged.episodes[0].nodes[0].protagonistPresence).toBe('offscreen');});+ it('preserves the render format when a v4 peer wins an unrelated LWW edit', async () => {+ let loom = await makeLoom({+ name: 'Local production',+ renderSettings: { formatId: 'portrait-9-16' },+ });+ loom = await updateLoom(loom.id, {+ productionStatus: {+ editorialApprovedAt: '2026-08-30T12:00:00.000Z',+ editorialApprovalSource: 'manual',+ deliveryApprovedAt: '2026-08-30T13:00:00.000Z',+ },+ });+ const remoteV4 = {+ ...loom,+ name: 'Renamed by v4 peer',+ updatedAt: '2099-01-01T00:00:00.000Z',+ renderSettings: undefined,+ productionStatus: undefined,+ };++ await mergeLoomsFromSync([remoteV4], { senderSchemaVersions: { fableLoom: 4 } });++ expect(await getLoom(loom.id)).toMatchObject({+ name: 'Renamed by v4 peer',+ renderSettings: {+ formatId: 'portrait-9-16', aspectRatio: '9:16', width: 576, height: 1024,+ },+ productionStatus: {+ editorialApprovedAt: '2026-08-30T12:00:00.000Z',+ editorialApprovalSource: 'manual',+ deliveryApprovedAt: '2026-08-30T13:00:00.000Z',+ },+ });+ });++ it('preserves playable challenge mappings when a v4 peer wins an unrelated edit', async () => {+ let loom = await makeLoom({ name: 'Local challenge plan' });+ loom = await addEpisode(loom.id, { title: 'Pilot' });+ const episodeId = loom.episodes[0].id;+ loom = await addNode(loom.id, episodeId, {+ title: 'The keypad', plotPointId: 'plot-lock', challengePhase: 'setup',+ });+ const nodeId = loom.episodes[0].nodes[0].id;+ loom = await updateLoom(loom.id, {+ seriesPlan: {+ storyArc: 'The courier crosses the first blockade.',+ plotPoints: [{+ id: 'plot-lock', kind: 'challenge', title: 'Open the sealed door',+ description: 'Recall the planted code.', episodeId,+ }],+ sideQuests: [],+ },+ });+ loom = await updateEpisode(loom.id, episodeId, {+ storyOutline: {+ startKey: nodeId,+ scenes: [{+ key: nodeId, title: 'The keypad', summary: 'The planted code becomes actionable.',+ plotPointId: 'plot-lock', challengePhase: 'setup', isEnding: true, transitions: [],+ }],+ validation: { status: 'draft', issues: [] },+ },+ });+ const remoteV4 = {+ ...loom,+ name: 'Renamed by v4 peer',+ updatedAt: '2099-01-01T00:00:00.000Z',+ seriesPlan: {+ ...loom.seriesPlan,+ plotPoints: loom.seriesPlan.plotPoints.map(({ kind: _kind, ...item }) => item),+ },+ episodes: loom.episodes.map((episode) => ({+ ...episode,+ storyOutline: {+ ...episode.storyOutline,+ scenes: episode.storyOutline.scenes.map(({+ plotPointId: _plotPointId, challengePhase: _challengePhase, ...scene+ }) => scene),+ },+ nodes: episode.nodes.map(({+ plotPointId: _plotPointId, challengePhase: _challengePhase, ...node+ }) => node),+ })),+ };++ await mergeLoomsFromSync([remoteV4], { senderSchemaVersions: { fableLoom: 4 } });+ const merged = await getLoom(loom.id);+ expect(merged.seriesPlan.plotPoints[0].kind).toBe('challenge');+ expect(merged.episodes[0].nodes[0]).toMatchObject({+ plotPointId: 'plot-lock', challengePhase: 'setup',+ });+ expect(merged.episodes[0].storyOutline.scenes[0]).toMatchObject({+ plotPointId: 'plot-lock', challengePhase: 'setup',+ });+ });+it('journals divergent story edits and can restore the authored snapshot', async () => {const local = await makeLoom({ name: 'Local story', premise: 'Local premise' });const base = { ...local, name: 'Shared story', premise: 'Shared premise' };@@ -433,21 +529,67 @@ describe('loom CRUD', () => {});});-describe('format and play settings round-trip', () => {+describe('format, render, and play settings round-trip', () => {it('keeps them across an unrelated patch, and accepts them at create', async () => {- const loom = await makeLoom({ format: 'teleplay', playSettings: { providerId: 'claude', model: 'opus', effort: null } });+ const loom = await makeLoom({+ format: 'teleplay',+ playSettings: { providerId: 'claude', model: 'opus', effort: null },+ renderSettings: { formatId: 'portrait-9-16' },+ });expect(loom.format).toBe('teleplay');expect(loom.playSettings).toEqual({ providerId: 'claude', model: 'opus', effort: null });+ expect(loom.renderSettings).toEqual({+ formatId: 'portrait-9-16', aspectRatio: '9:16', width: 576, height: 1024,+ });// A rename must not silently reset the pin or the format — the exact drift// a PATCH_FIELDS / schema mismatch would produce.const renamed = await updateLoom(loom.id, { name: 'Renamed' });expect(renamed.format).toBe('teleplay');expect(renamed.playSettings).toEqual({ providerId: 'claude', model: 'opus', effort: null });+ expect(renamed.renderSettings).toEqual(loom.renderSettings);const cleared = await updateLoom(loom.id, { playSettings: null });expect(cleared.playSettings).toBeNull();expect(cleared.format).toBe('teleplay');+ expect(cleared.renderSettings).toEqual(loom.renderSettings);+ });++ it('backfills an explicit 16:9 default for existing records', async () => {+ const loom = await makeLoom();+ expect(loom.renderSettings).toEqual({+ formatId: 'landscape-16-9', aspectRatio: '16:9', width: 1024, height: 576,+ });+ });++ it('reopens only the production approvals affected by a later change', async () => {+ let loom = await makeLoom({ premise: 'A courier must cross the city.' });+ loom = await addEpisode(loom.id, { title: 'Pilot' });+ loom = await addNode(loom.id, loom.episodes[0].id, { title: 'Opening' });+ loom = await updateLoom(loom.id, {+ productionStatus: {+ editorialApprovedAt: '2026-08-30T12:00:00.000Z',+ editorialApprovalSource: 'manual',+ deliveryApprovedAt: '2026-08-30T13:00:00.000Z',+ },+ });++ await attachNodeImage(loom.id, loom.episodes[0].id, loom.episodes[0].nodes[0].id, {+ filename: 'new-storyboard.png', jobId: 'job-storyboard',+ });+ let updated = await getLoom(loom.id);+ expect(updated.productionStatus).toMatchObject({+ editorialApprovedAt: '2026-08-30T12:00:00.000Z',+ editorialApprovalSource: 'manual',+ deliveryApprovedAt: null,+ });++ updated = await updateLoom(loom.id, { premise: 'A courier must cross a flooded city.' });+ expect(updated.productionStatus).toEqual({+ editorialApprovedAt: null,+ editorialApprovalSource: null,+ deliveryApprovedAt: null,+ });});});@@ -485,7 +627,7 @@ describe('series plan round-trip', () => {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 }],+ plotPoints: [{ id: 'plot-1', kind: 'beat', 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 });@@ -590,7 +732,7 @@ describe('nodes and transitions', () => {it('demotes a validated outline when a scene contract changes, but not for prose', async () => {const { loomId, episodeId } = await setup();- let updated = await addNode(loomId, episodeId, { title: 'Opening' });+ let updated = await addNode(loomId, episodeId, { title: 'Opening', playbackMode: 'cut' });updated = await addNode(loomId, episodeId, { title: 'Ending', isEnding: true });const [opening, ending] = updated.episodes[0].nodes;const withPath = await addNodeTransition(loomId, episodeId, opening.id, {@@ -771,6 +913,40 @@ describe('attachNodeImage', () => {expect(attached.visualConditioning.bindings.injected).toBeUndefined();});+ it('drops stale image provenance while retaining video provenance on replacement', async () => {+ const loom = await makeLoom();+ let updated = await addEpisode(loom.id, {});+ const episodeId = updated.episodes[0].id;+ updated = await addNode(loom.id, episodeId, {+ title: 'A',+ playbackAssets: {+ visualConditioningByAsset: {+ 'old-still': {+ version: 1, compilerVersion: 'visual-v1', status: 'locked', assetId: 'old-still',+ capability: { kind: 'image', backend: 'local' },+ },+ 'entry-video': {+ version: 1, compilerVersion: 'visual-v1', status: 'locked', assetId: 'entry-video',+ capability: { kind: 'video', backend: 'local' },+ },+ },+ },+ });++ const attached = await attachNodeImage(loom.id, episodeId, updated.episodes[0].nodes[0].id, {+ filename: 'replacement.png',+ jobId: 'job-replacement',+ visualConditioning: {+ version: 1, compilerVersion: 'visual-v1', status: 'locked', assetId: 'new-still',+ capability: { kind: 'image', backend: 'local' },+ },+ });++ expect(attached.playbackAssets.visualConditioningByAsset).not.toHaveProperty('old-still');+ expect(attached.playbackAssets.visualConditioningByAsset).toHaveProperty('entry-video');+ expect(attached.playbackAssets.visualConditioningByAsset).toHaveProperty('new-still');+ });+it('returns null (no throw) when the target is gone or the filename is unsafe', async () => {const loom = await makeLoom();const updated = await addEpisode(loom.id, {});diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex a022cd7742..0fe2d68bac 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -30,6 +30,9 @@ import {analyzeStoryOutline,analyzeStoryOutlineTeleplaySync,describeStoryOutlineForPrompt,+ fableLoomEpisodeChallenges,+ fableLoomPlotPointKind,+ isStoryOutlineTeleplaySyncIssue,sanitizeStoryOutline,} from '../../lib/fableLoomOutline.js';import {@@ -152,10 +155,15 @@ const seriesPlanContext = (loom, episode) => {? [...items].sort((a, b) => Number(matchesEpisode(b, episode.id)) - Number(matchesEpisode(a, episode.id))): items;const plotPoints = relevantFirst(plan.plotPoints || [], (item, id) => item.episodeId === id)- .slice(0, 12).map((item, index) => {const assignment = item.episodeId ? ` [planned for ${episodeLabels.get(item.episodeId) || item.episodeId}]` : ' [unassigned]';- return `Plot point ${index + 1}${assignment}: ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`;+ const challenge = fableLoomPlotPointKind(item) === 'challenge';+ return [+ `Plot point ${index + 1} id=${item.id} kind=${challenge ? 'challenge' : 'beat'}${assignment}: ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 700)}` : ''}`,+ challenge+ ? 'PLAYABLE CHALLENGE CONTRACT: map this exact plot-point id onto separate outline/teleplay beats with challengePhase values setup, decision, success, failure, and recovery. The setup must lead to the decision loop; the decision must reach both success and failure; both outcomes must continue to recovery/payoff. Failure continues with a visible cost rather than resetting or dead-ending.'+ : '',+ ].filter(Boolean).join('\n');});const sideQuests = relevantFirst(plan.sideQuests || [], (item, id) => item.startEpisodeId === id || item.endEpisodeId === id).slice(0, 12)@@ -278,6 +286,8 @@ const seriesPlanGenerationFingerprint = (loom) => JSON.stringify({const generatedNodeFields = (raw) => ({title: raw.title,prose: raw.prose,+ plotPointId: raw.plotPointId,+ challengePhase: raw.challengePhase,imagePrompt: raw.imagePrompt,videoPrompt: raw.videoPrompt,cameraMovement: raw.cameraMovement,@@ -358,6 +368,7 @@ const outlineStructuralAnalysis = (loom, episode) => {const structural = analyzeStoryOutline(episode.storyOutline, {participationMode: loom.participationMode,requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),+ challenges: fableLoomEpisodeChallenges(loom, episode.id),});const teleplaySync = analyzeStoryOutlineTeleplaySync(episode, episode.storyOutline, {participationMode: loom.participationMode,@@ -413,6 +424,7 @@ export async function generateEpisodeOutline(loomId, episodeId, {const validation = analyzeStoryOutline(outline, {participationMode: loom.participationMode,requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),+ challenges: fableLoomEpisodeChallenges(loom, episode.id),});const draft = {...outline,@@ -477,14 +489,37 @@ export async function weaveEpisode(loomId, episodeId, {const loom = await requireLoom(loomId);const episode = findEpisode(loom, episodeId);const outlineValidation = expandFromOutline ? outlineStructuralAnalysis(loom, episode) : null;- if (expandFromOutline && episode.storyOutline?.validation?.status !== 'valid') {+ const outlineStoryValidation = expandFromOutline+ ? analyzeStoryOutline(episode.storyOutline, {+ participationMode: loom.participationMode,+ requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),+ challenges: fableLoomEpisodeChallenges(loom, episode.id),+ })+ : null;+ const currentOutlineErrors = expandFromOutline+ ? outlineValidation.issues.filter((issue) => issue.severity !== 'warning')+ : [];+ const replacingChangedTeleplay = Boolean(+ expandFromOutline+ && replace+ && episode.nodes.length+ && episode.storyOutline?.validation?.status === 'invalid'+ && outlineStoryValidation?.stats?.errorCount === 0+ && currentOutlineErrors.length+ && currentOutlineErrors.every(isStoryOutlineTeleplaySyncIssue),+ );+ if (expandFromOutline+ && episode.storyOutline?.validation?.status !== 'valid'+ && !replacingChangedTeleplay) {throw outlineInvalidError(outlineValidation);}- if (expandFromOutline && outlineValidation.stats.errorCount) {+ if (expandFromOutline && outlineValidation.stats.errorCount && !replacingChangedTeleplay) {throw outlineInvalidError(outlineValidation);}if (expandFromOutline) {- const seriesOutlineValidation = analyzeSeriesStoryOutlines(loom);+ const seriesOutlineValidation = analyzeSeriesStoryOutlines(loom, {+ ...(replacingChangedTeleplay ? { replacingEpisodeId: episode.id } : {}),+ });if (seriesOutlineValidation.stats.errorCount) {const firstIssue = seriesOutlineValidation.issues.find((issue) => issue.severity === 'error');throw new ServerError(`Complete the series beat outlines before expansion: ${firstIssue.message}`, {@@ -515,10 +550,37 @@ export async function weaveEpisode(loomId, episodeId, {action: 'weave-episode', label: 'Weaving episode', source: 'fableloom-weave',});- const { nodes, startNodeId, idByKey } = mapGeneratedGraph(content);- const expandedOutline = expandFromOutline+ const { nodes: generatedNodes, startNodeId, idByKey } = mapGeneratedGraph(content);+ const remappedOutline = expandFromOutline? remapOutlineToExpandedNodeIds(episode.storyOutline, idByKey): null;+ const remappedOutlineByNodeId = new Map((remappedOutline?.scenes || [])+ .map((scene) => [scene.key, scene]));+ const nodes = generatedNodes.map((node) => {+ const outlineScene = remappedOutlineByNodeId.get(node.id);+ return outlineScene ? {+ ...node,+ plotPointId: outlineScene.plotPointId || null,+ challengePhase: outlineScene.challengePhase || null,+ } : node;+ });+ const remappedOutlineValidation = remappedOutline+ ? analyzeStoryOutline(remappedOutline, {+ participationMode: loom.participationMode,+ requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),+ challenges: fableLoomEpisodeChallenges(loom, episode.id),+ })+ : null;+ const expandedOutline = remappedOutline+ ? {+ ...remappedOutline,+ validation: {+ status: remappedOutlineValidation.stats.errorCount ? 'invalid' : 'valid',+ issues: remappedOutlineValidation.issues,+ validatedAt: new Date().toISOString(),+ },+ }+ : null;if (expandedOutline) {const sync = analyzeStoryOutlineTeleplaySync({ ...episode, nodes, startNodeId },@@ -884,7 +946,8 @@ export async function generateSeriesPlan(loomId, { providerId, model, effort, opconst isUsablePlanItem = (item) => item && typeof item === 'object'&& ((isStr(item.title) && item.title.trim()) || (isStr(item.description) && item.description.trim()));const plotPoints = (Array.isArray(content?.plotPoints) ? content.plotPoints : [])- .filter(isUsablePlanItem);+ .filter(isUsablePlanItem)+ .map((item) => ({ ...item, kind: fableLoomPlotPointKind(item) }));const sideQuests = (Array.isArray(content?.sideQuests) ? content.sideQuests : []).filter(isUsablePlanItem);if (!storyArc.trim() || !plotPoints.length || !sideQuests.length) {@@ -1006,7 +1069,7 @@ export async function feedbackSeriesPlan(loomId, {const plan = { ...current.seriesPlan };if (hasOwn(content, 'storyArc') && typeof content.storyArc === 'string') plan.storyArc = content.storyArc;plan.plotPoints = applyPlanItemEdits(plan.plotPoints, content.plotPointEdits, content.plotPointOrder, {- prefix: 'plot', fields: ['title', 'description', 'episodeId'],+ prefix: 'plot', fields: ['kind', 'title', 'description', 'episodeId'],});plan.sideQuests = applyPlanItemEdits(plan.sideQuests, content.sideQuestEdits, content.sideQuestOrder, {prefix: 'quest', fields: ['title', 'description', 'status', 'startEpisodeId', 'endEpisodeId'],diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.jsindex ab17025ac2..7c9fa8ca0d 100644--- a/server/services/fableLoom/weave.test.js+++ b/server/services/fableLoom/weave.test.js@@ -22,7 +22,9 @@ vi.mock('../universeBuilder.js', () => ({ getUniverse: getUniverseMock }));const getSeriesMock = vi.hoisted(() => vi.fn(async () => null));vi.mock('../pipeline/series.js', () => ({ getSeries: getSeriesMock }));-const { createLoom, addEpisode, addNode, mutateLoom, updateLoom, updateNode, getLoom } = await import('./records.js');+const {+ createLoom, addEpisode, addNode, mutateLoom, updateEpisode, updateLoom, updateNode, getLoom,+} = await import('./records.js');const { _resetFableLoomBackend } = await import('./store.js');const { aiStatusEvents } = await import('../aiStatusEvents.js');const {@@ -102,6 +104,59 @@ const generatedGraphFromOutline = () => ({],});+const generatedChallengeOutline = () => ({+ startKey: 'setup',+ scenes: [+ {+ key: 'setup', title: 'The keypad', summary: 'A prior scene planted the code now needed at the sealed door.',+ plotPointId: 'plot-challenge', challengePhase: 'setup', playbackMode: 'cut',+ transitions: [{ targetKey: 'decision', intent: 'try the lock' }],+ },+ {+ key: 'decision', title: 'Recall the code', summary: 'The viewer chooses which remembered code the courier enters.',+ plotPointId: 'plot-challenge', challengePhase: 'decision', playbackMode: 'decision',+ transitions: [+ { targetKey: 'success', intent: 'enter the remembered code' },+ { targetKey: 'failure', intent: 'guess before the guard returns' },+ ],+ },+ {+ key: 'success', title: 'Quiet entry', summary: 'The right code opens the door without alerting the guard.',+ plotPointId: 'plot-challenge', challengePhase: 'success', playbackMode: 'cut',+ transitions: [{ targetKey: 'recovery', intent: 'slip inside' }],+ },+ {+ key: 'failure', title: 'Alarm chirp', summary: 'The wrong code alerts the guard but leaves a costly escape.',+ plotPointId: 'plot-challenge', challengePhase: 'failure', playbackMode: 'cut',+ transitions: [{ targetKey: 'recovery', intent: 'create a distraction' }],+ },+ {+ key: 'recovery', title: 'Past the blockade', summary: 'Both outcomes continue inside with their different costs intact.',+ plotPointId: 'plot-challenge', challengePhase: 'recovery', playbackMode: 'cut',+ transitions: [{ targetKey: 'ending', intent: 'move deeper inside' }],+ },+ {+ key: 'ending', title: 'Inside', summary: 'The courier reaches the next obstacle.',+ isEnding: true, endingLabel: 'Through the door', transitions: [],+ },+ ],+});++const generatedChallengeGraph = () => ({+ startKey: 'setup',+ nodes: generatedChallengeOutline().scenes.map((scene) => ({+ key: scene.key,+ title: scene.title,+ prose: `Teleplay for ${scene.title}.`,+ playbackMode: scene.playbackMode || 'decision',+ audienceConnection: 'disconnected',+ protagonistPresence: 'onscreen',+ isEnding: scene.isEnding === true,+ endingLabel: scene.endingLabel || '',+ transitions: scene.transitions || [],+ })),+});+describe('mapGeneratedGraph', () => {it('mints server ids, remaps targets, and drops unknown-target transitions', () => {const { nodes, startNodeId } = mapGeneratedGraph(generatedGraph());@@ -228,6 +283,63 @@ describe('weaveEpisode', () => {expect(runStagedLLM.mock.calls[1][1].outlineDigest).toContain('[s1] Signal');});+ it('replaces an old teleplay after a structurally valid outline rewrite', async () => {+ const { loomId, episodeId } = await setup();+ runStagedLLM.mockResolvedValueOnce({ content: generatedOutline(), runId: 'outline-run' });+ await generateEpisodeOutline(loomId, episodeId, {});+ await validateEpisodeOutline(loomId, episodeId);+ runStagedLLM.mockResolvedValueOnce({ content: generatedGraphFromOutline(), runId: 'first-expand' });+ await weaveEpisode(loomId, episodeId, { expandFromOutline: true });++ const expanded = await getLoom(loomId);+ const expandedEpisode = expanded.episodes[0];+ const revisedOutline = {+ ...expandedEpisode.storyOutline,+ scenes: expandedEpisode.storyOutline.scenes.map((scene, index) => (+ index === 0 ? { ...scene, title: 'Revised signal' } : scene+ )),+ };+ await updateEpisode(loomId, episodeId, { storyOutline: revisedOutline });+ const checked = await validateEpisodeOutline(loomId, episodeId);++ expect(checked.outline.validation.status).toBe('invalid');+ expect(checked.validation.issues.every((issue) => (+ issue.code.startsWith('TELEPLAY_')+ ))).toBe(true);++ const replacementOutline = checked.outline;+ const replacementGraph = {+ startKey: replacementOutline.startKey,+ nodes: replacementOutline.scenes.map((scene) => ({+ key: scene.key,+ title: scene.title,+ prose: `${scene.title} in full teleplay form.`,+ playbackMode: scene.playbackMode,+ audienceConnection: scene.audienceConnection,+ protagonistPresence: scene.protagonistPresence,+ isEnding: scene.isEnding,+ endingLabel: scene.endingLabel,+ transitions: scene.transitions.map((transition) => ({+ targetKey: transition.targetKey,+ intent: transition.intent,+ })),+ })),+ };+ runStagedLLM.mockResolvedValueOnce({ content: replacementGraph, runId: 'replacement-expand' });++ const replaced = await weaveEpisode(loomId, episodeId, {+ replace: true,+ expandFromOutline: true,+ });++ expect(replaced.runId).toBe('replacement-expand');+ expect(replaced.loom.episodes[0].nodes[0].title).toBe('Revised signal');+ expect(replaced.loom.episodes[0].storyOutline.validation).toMatchObject({+ status: 'valid',+ issues: [],+ });+ });+it('uses the loom participation mode when normalizing helper outline beats', async () => {const { loomId, episodeId } = await setup();await updateLoom(loomId, {@@ -1054,8 +1166,41 @@ describe('series plan AI', () => {runStagedLLM.mockResolvedValueOnce({ content: generatedGraph(), runId: 'run-weave' });await weaveEpisode(loomId, episodeId, { replace: true });expect(runStagedLLM).toHaveBeenCalledWith('fableloom-weave-episode', expect.objectContaining({- storyContext: expect.stringContaining('Plot point 1 [planned for Episode 1: Pilot]: Episode turn'),+ storyContext: expect.stringContaining('Plot point 1 id=plot-relevant kind=beat [planned for Episode 1: Pilot]: Episode turn'),+ }), expect.anything());+ });++ it('expands explicitly-authored challenges into a multi-scene interactive contract', async () => {+ const { loomId, episodeId } = await setup();+ await updateLoom(loomId, { seriesPlan: {+ storyArc: 'A courier earns a dangerous passage.',+ plotPoints: [{+ id: 'plot-challenge',+ kind: 'challenge',+ title: 'Recall the gate code',+ description: 'SETUP: Plant the code. VIEWER DECISION LOOP: Recall it. FAILURE: Trigger pursuit.',+ episodeId,+ }],+ sideQuests: [],+ } });+ runStagedLLM.mockResolvedValueOnce({ content: generatedChallengeOutline(), runId: 'outline-challenge' });+ await generateEpisodeOutline(loomId, episodeId, {});++ expect(runStagedLLM).toHaveBeenCalledWith('fableloom-outline-episode', expect.objectContaining({+ storyContext: expect.stringContaining('PLAYABLE CHALLENGE CONTRACT'),}), expect.anything());+ expect(runStagedLLM.mock.calls[0][1].storyContext).toContain('Failure continues with a visible cost');+ expect((await validateEpisodeOutline(loomId, episodeId)).outline.validation.status).toBe('valid');++ runStagedLLM.mockResolvedValueOnce({ content: generatedChallengeGraph(), runId: 'expand-challenge' });+ const expanded = await weaveEpisode(loomId, episodeId, { expandFromOutline: true });+ const challengeNodes = expanded.loom.episodes[0].nodes.filter((node) => (+ node.plotPointId === 'plot-challenge'+ ));+ expect(challengeNodes.map((node) => node.challengePhase).sort()).toEqual([+ 'decision', 'failure', 'recovery', 'setup', 'success',+ ]);+ expect(expanded.loom.episodes[0].storyOutline.validation.status).toBe('valid');});it('carries enabled series delivery beats into episode context and preserves them during plan drafting', async () => {diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.jsindex 97a7cc7a30..9f7084b592 100644--- a/server/services/tuiPromptRunner.js+++ b/server/services/tuiPromptRunner.js@@ -273,6 +273,24 @@ ${prompt}`;throw new Error(`Failed to spawn TUI '${command}': ${err.message}`);}+ // Subscribe to exit IMMEDIATELY after spawn. A CLI can fail before its first+ // paint (bad local config, an early runtime crash, etc.); the rest of this+ // function registers the run, Shell view, and completion machinery before it+ // used to attach onExit. node-pty does not replay an already-delivered exit,+ // so that small window stranded the run until its hard timeout. Queue the+ // one exit event until finish() and the timers below are ready, then replay it+ // through the ordinary exit path. This is a startup/lifecycle guard, not an+ // output-idle timeout: a live but quiet model remains untouched.+ let dispatchPtyExit = null;+ let pendingPtyExit = null;+ ptyProcess.onExit((event) => {+ if (dispatchPtyExit) {+ dispatchPtyExit(event);+ return;+ }+ pendingPtyExit = pendingPtyExit || event;+ });+// Register in the same active-runs map the patched stopRun/isRunActive// consult, so /runs UI can stop a hung TUI run. Without this, stopRun is a// no-op for TUI and isRunActive returns false — the PTY keeps spending@@ -671,7 +689,7 @@ ${prompt}`;}});- ptyProcess.onExit(({ exitCode, signal }) => {+ const handlePtyExit = ({ exitCode, signal }) => {const killed = !!signal;// pm2 tree-kills descendants during a PortOS restart, while /runs Stop// kills this registered PTY through runner.stopRun. Both are intentional@@ -722,7 +740,7 @@ ${prompt}`;reason: hostInterrupted ? 'host-shutdown' : (stopRequested ? 'canceled' : (killed ? 'killed' : 'exit')),canceled,});- });+ };const sendPrompt = (reason) => {if (finalized || promptSentAt) return;@@ -966,6 +984,17 @@ ${prompt}`;reason: 'timeout'});}, totalTimeoutMs);++ // The exit bridge was attached immediately after spawn. Hand it the fully+ // initialized lifecycle only after every cleanup-owned timer exists, then+ // replay an exit that arrived during setup. Assign before reading the+ // pending slot so an exit racing this handoff is delivered exactly once.+ dispatchPtyExit = handlePtyExit;+ if (pendingPtyExit) {+ const earlyExit = pendingPtyExit;+ pendingPtyExit = null;+ handlePtyExit(earlyExit);+ }});}diff --git a/server/services/tuiPromptRunner.test.js b/server/services/tuiPromptRunner.test.jsindex 8965ad32da..da753e1b3b 100644--- a/server/services/tuiPromptRunner.test.js+++ b/server/services/tuiPromptRunner.test.js@@ -508,6 +508,37 @@ describe('executeTuiRun', () => {await promise;});+ it('finalizes when the PTY exits during startup before the lifecycle is ready', async () => {+ const earlyExitPty = makeFakePty();+ earlyExitPty.onExit.mockImplementation((handler) => {+ earlyExitPty._exitHandler = handler;+ handler({ exitCode: 1, signal: null });+ });+ ptySpawnMock.mockReturnValueOnce(earlyExitPty);+ const onComplete = vi.fn();+ const provider = { id: 'codex', type: 'tui', command: 'codex' };++ await expect(executeTuiRun({+ runId: 'run-early-exit',+ provider,+ prompt: 'return a response long enough for the prompt guard',+ workspacePath: TEST_WORKSPACE,+ onComplete,+ timeout: 60000,+ })).resolves.toBeUndefined();++ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-early-exit',+ success: false,+ exitCode: 1,+ error: 'TUI exited with code 1',+ extras: expect.objectContaining({ completionReason: 'exit' }),+ }));+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ success: false, exitCode: 1 }));+ expect(runnerMocks.unregisterActiveRun).toHaveBeenCalledWith('run-early-exit');+ expect(shellMocks.unregisterExternalSession).toHaveBeenCalledWith('run-early-exit', { exitCode: 1 });+ });+it('registers a read-only Shell view (labelled by source) and tears it down on finish', async () => {const provider = { id: 'claude', type: 'tui', command: 'claude', defaultModel: 'claude-fable-5' };const onReady = vi.fn();