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
scope FableLoom reformat to one episode per request so a large loom cannot time out (#4794)
[._.]/ Adam Eivy5bf229a989aa
diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsxindex 06ae3bde8b..de34c771d0 100644--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx@@ -14,7 +14,7 @@* all, so this only governs typed input.*/-import { useRef } from 'react';+import { useRef, useState } from 'react';import { Loader2, Sparkles } from 'lucide-react';import Drawer from '../Drawer';import ProviderModelSelector from '../ProviderModelSelector';@@ -23,16 +23,37 @@ import toast from '../ui/Toast';import useProviderModels from '../../hooks/useProviderModels';import { useAsyncAction } from '../../hooks/useAsyncAction';import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providers';-import { reformatLoom, updateLoom } from '../../services/api';+import { reformatLoomEpisode, updateLoom } from '../../services/api';import { fieldClass, labelClass } from './fieldStyles';-import { LOOM_FORMATS, loomFormatHint, loomFormatLabel } from './loomFormats';+import { LOOM_FORMATS, episodesNeedingReformat, loomFormatHint, loomFormatLabel } from './loomFormats';++/**+ * The one line of feedback a multi-minute rewrite gives. Built as a single+ * string so the walk reads as one sentence rather than as fragments a screen+ * reader announces separately.+ */+const rewriteProgressLabel = ({ index, total, title, scenesLeft }) => [+ `Rewriting episode ${index} of ${total}`,+ title ? ` — ${title}` : '',+ '…',+ scenesLeft ? ` ${scenesLeft} scene${scenesLeft === 1 ? '' : 's'} left in it.` : '',+].join('');export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate, onRewritten }) {const { providers } = useProviderModels({ allowDefault: true, silent: true, withEffort: true });+ // Which episode the rewrite is on. The walk is one request per episode, so+ // this is the only feedback a multi-minute pass gives — without it the button+ // spins for minutes with nothing to show which of five episodes is in flight.+ const [rewritingEpisode, setRewritingEpisode] = useState(null);+const format = loom.format || 'prose';const play = loom.playSettings || {};const playProvider = providers.find((p) => p.id === play.providerId);+ // Only scenes not already in the target format are sent, so this is what the+ // rewrite will actually cost — and it ticks down as each episode lands.+ const pendingEpisodes = episodesNeedingReformat(loom, format);+ const pendingScenes = pendingEpisodes.reduce((total, e) => total + e.sceneCount, 0);const sceneCount = loom.episodes.reduce((total, ep) => total + ep.nodes.length, 0);// The rewrite reads the format pin SERVER-side, so it stays disabled while a@@ -59,22 +80,56 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,return patch({ playSettings: { ...pendingPlay.current } });};+ // One request per episode. A whole-loom rewrite used to run every provider+ // call behind a single held request — minutes long, with a fetch timeout free+ // to kill the response while the server kept writing. The loom's format pin+ // is still the SERVER's call: it lands only once no episode has an+ // unconverted scene left, so a walk interrupted here can't leave the loom+ // claiming a format half its story isn't in.+ //// `onRewritten` fires on BOTH paths on purpose. A rewrite persists each// chunk as it lands, so even a run that throws part-way has already changed// scene text on the server — any editor still holding the pre-rewrite text// would write it back on its next blur-save.const [runReformat, reformatting] = useAsyncAction(async () => {- // Clear the scene selection UP FRONT. A multi-chunk run takes minutes, and+ // Clear the scene selection UP FRONT. A multi-episode run takes minutes, and// the page underneath stays interactive — an editor still holding the// pre-rewrite text would write it back on any blur during that window, not// just after the run settles.onRewritten?.({ refetch: false });- const result = await reformatLoom(loom.id, { format }, { silent: true })- .finally(() => onRewritten?.());- onLoomUpdate(result.loom);- toast.success(result.remaining- ? `Rewrote ${result.rewritten} scene${result.rewritten === 1 ? '' : 's'} — ${result.remaining} left, run it again to finish`- : `Rewrote ${result.rewritten} scene${result.rewritten === 1 ? '' : 's'} as ${loomFormatLabel(format).toLowerCase()}`);+ // The walk is the snapshot this closure captured: folding each response+ // back in re-renders the drawer with a shorter pending list, and iterating+ // the live one would drop episodes out from under the loop.+ const walk = pendingEpisodes;+ let rewritten = 0;+ let remaining = 0;+ try {+ for (const [index, { episode }] of walk.entries()) {+ let scenesLeft = null;+ // A long episode comes back `capped` — the request stopped at its own+ // ceiling with scenes it never sent. Asking again continues from there,+ // and each pass rewrites at least one scene, so this terminates. A+ // response that is NOT capped is done with this episode even if the+ // model dropped a scene: re-sending a refusal isn't progress, and the+ // leftover is reported in the "run it again to finish" toast.+ do {+ setRewritingEpisode({ title: episode.title, index: index + 1, total: walk.length, scenesLeft });+ const result = await reformatLoomEpisode(loom.id, episode.id, { format }, { silent: true });+ rewritten += result.rewritten;+ remaining = result.remaining;+ scenesLeft = result.capped ? result.episodeRemaining : null;+ // Fold each response back in as it lands, so the pending count and the+ // story underneath track the run instead of jumping at the end.+ onLoomUpdate(result.loom);+ } while (scenesLeft);+ }+ } finally {+ setRewritingEpisode(null);+ onRewritten?.();+ }+ toast.success(remaining+ ? `Rewrote ${rewritten} scene${rewritten === 1 ? '' : 's'} — ${remaining} left, run it again to finish`+ : `Rewrote ${rewritten} scene${rewritten === 1 ? '' : 's'} as ${loomFormatLabel(format).toLowerCase()}`);}, { errorMessage: 'The rewrite failed' });return (@@ -102,8 +157,9 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,<p className="text-xs text-port-text-muted">{loomFormatHint(format)} New scenes are written this way — scenesyou already have keep their current text until you rewrite them.+ {sceneCount > 0 && pendingScenes === 0 && ` Every scene you have is already written as ${loomFormatLabel(format).toLowerCase()}.`}</p>- {sceneCount > 0 && (+ {pendingScenes > 0 && (<buttontype="button"onClick={runReformat}@@ -113,9 +169,14 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,{reformatting ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}{reformatting? 'Rewriting…'- : `Rewrite all ${sceneCount} scene${sceneCount === 1 ? '' : 's'} as ${loomFormatLabel(format).toLowerCase()}`}+ : `Rewrite ${pendingScenes} scene${pendingScenes === 1 ? '' : 's'} as ${loomFormatLabel(format).toLowerCase()}`}</button>)}+ {rewritingEpisode && (+ <p className="text-xs text-port-text-muted" aria-live="polite">+ {rewriteProgressLabel(rewritingEpisode)}+ </p>+ )}</section><section className="border-t border-port-border pt-4 space-y-2">diff --git a/client/src/components/fableloom/LoomSettingsDrawer.test.jsx b/client/src/components/fableloom/LoomSettingsDrawer.test.jsxnew file mode 100644index 0000000000..bf46949351--- /dev/null+++ b/client/src/components/fableloom/LoomSettingsDrawer.test.jsx@@ -0,0 +1,161 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../services/api', () => ({+ reformatLoomEpisode: vi.fn(),+ updateLoom: vi.fn(),+}));+vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [] }) }));+vi.mock('../ProviderModelSelector', () => ({ default: () => null }));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++import { reformatLoomEpisode } from '../../services/api';+import toast from '../ui/Toast';+import LoomSettingsDrawer from './LoomSettingsDrawer';++const scene = (id, format) => ({ id, title: id, prose: `Prose for ${id}.`, format, transitions: [] });++// Two episodes, all scenes still prose while the loom is pinned to teleplay —+// the state right after an author flips the format select.+const makeLoom = (episodes) => ({+ id: 'loom-1',+ name: 'Example Loom',+ format: 'teleplay',+ playSettings: {},+ episodes,+});++const twoEpisodes = () => makeLoom([+ { id: 'ep-1', title: 'Pilot', nodes: [scene('s1'), scene('s2')] },+ { id: 'ep-2', title: 'Second', nodes: [scene('s3')] },+]);++const renderDrawer = (loom, props = {}) => {+ const onLoomUpdate = vi.fn();+ const onRewritten = vi.fn();+ render(+ <LoomSettingsDrawer+ open+ onClose={() => {}}+ loom={loom}+ onLoomUpdate={onLoomUpdate}+ onRewritten={onRewritten}+ {...props}+ />,+ );+ return { onLoomUpdate, onRewritten };+};++const clickRewrite = (user) => user.click(screen.getByRole('button', { name: /^Rewrite \d+ scene/ }));++beforeEach(() => vi.clearAllMocks());++describe('LoomSettingsDrawer rewrite', () => {+ it('walks the episodes one request at a time instead of one request for the loom', async () => {+ const user = userEvent.setup();+ const loom = twoEpisodes();+ reformatLoomEpisode+ .mockResolvedValueOnce({ loom, rewritten: 2, episodeRemaining: 0, remaining: 1, capped: false })+ .mockResolvedValueOnce({ loom, rewritten: 1, episodeRemaining: 0, remaining: 0, capped: false });+ const { onLoomUpdate } = renderDrawer(loom);++ // The count is the scenes that still need converting, not every scene.+ expect(screen.getByRole('button', { name: 'Rewrite 3 scenes as teleplay' })).toBeInTheDocument();+ await clickRewrite(user);++ await waitFor(() => expect(reformatLoomEpisode).toHaveBeenCalledTimes(2));+ expect(reformatLoomEpisode.mock.calls.map((c) => c[1])).toEqual(['ep-1', 'ep-2']);+ expect(reformatLoomEpisode.mock.calls[0][2]).toEqual({ format: 'teleplay' });+ // Each response folds back in as it lands rather than after the whole walk.+ expect(onLoomUpdate).toHaveBeenCalledTimes(2);+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Rewrote 3 scenes as teleplay'));+ });++ it('names the episode in flight', async () => {+ const user = userEvent.setup();+ const loom = twoEpisodes();+ // Both calls stay pending until released, so each episode's line is+ // observable rather than a frame that flashes past.+ const release = [];+ reformatLoomEpisode.mockImplementation(() => new Promise((resolve) => { release.push(resolve); }));+ renderDrawer(loom);+ await clickRewrite(user);++ expect(await screen.findByText('Rewriting episode 1 of 2 — Pilot…')).toBeInTheDocument();+ release[0]({ loom, rewritten: 2, episodeRemaining: 0, remaining: 1, capped: false });+ expect(await screen.findByText('Rewriting episode 2 of 2 — Second…')).toBeInTheDocument();++ release[1]({ loom, rewritten: 1, episodeRemaining: 0, remaining: 0, capped: false });+ await waitFor(() => expect(toast.success).toHaveBeenCalled());+ expect(screen.queryByText(/Rewriting episode/)).not.toBeInTheDocument();+ });++ it('says how much of a long episode is left while it re-asks', async () => {+ const user = userEvent.setup();+ const loom = makeLoom([{ id: 'ep-1', title: 'Pilot', nodes: [scene('s1')] }]);+ const release = [];+ reformatLoomEpisode.mockImplementation(() => new Promise((resolve) => { release.push(resolve); }));+ renderDrawer(loom);+ await clickRewrite(user);++ expect(await screen.findByText('Rewriting episode 1 of 1 — Pilot…')).toBeInTheDocument();+ release[0]({ loom, rewritten: 20, episodeRemaining: 5, remaining: 5, capped: true });+ expect(await screen.findByText('Rewriting episode 1 of 1 — Pilot… 5 scenes left in it.')).toBeInTheDocument();+ release[1]({ loom, rewritten: 5, episodeRemaining: 0, remaining: 0, capped: false });+ await waitFor(() => expect(toast.success).toHaveBeenCalled());+ });++ it('asks the same episode again while the server says it stopped at its ceiling', async () => {+ const user = userEvent.setup();+ const loom = makeLoom([{ id: 'ep-1', title: 'Pilot', nodes: [scene('s1')] }]);+ reformatLoomEpisode+ .mockResolvedValueOnce({ loom, rewritten: 20, episodeRemaining: 5, remaining: 5, capped: true })+ .mockResolvedValueOnce({ loom, rewritten: 5, episodeRemaining: 0, remaining: 0, capped: false });+ renderDrawer(loom);+ await clickRewrite(user);++ await waitFor(() => expect(reformatLoomEpisode).toHaveBeenCalledTimes(2));+ expect(reformatLoomEpisode.mock.calls.map((c) => c[1])).toEqual(['ep-1', 'ep-1']);+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Rewrote 25 scenes as teleplay'));+ });++ it('does NOT re-ask an episode the model merely dropped scenes in', async () => {+ const user = userEvent.setup();+ const loom = makeLoom([{ id: 'ep-1', title: 'Pilot', nodes: [scene('s1'), scene('s2')] }]);+ // Not capped: nothing went unsent, so asking again would only re-send a+ // refusal. The leftover rides the toast instead.+ reformatLoomEpisode.mockResolvedValue({ loom, rewritten: 1, episodeRemaining: 1, remaining: 1, capped: false });+ renderDrawer(loom);+ await clickRewrite(user);++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(+ 'Rewrote 1 scene — 1 left, run it again to finish',+ ));+ expect(reformatLoomEpisode).toHaveBeenCalledTimes(1);+ });++ it('stops the walk when an episode fails, keeping what the earlier ones wrote', async () => {+ const user = userEvent.setup();+ const loom = twoEpisodes();+ reformatLoomEpisode+ .mockResolvedValueOnce({ loom, rewritten: 2, episodeRemaining: 0, remaining: 1, capped: false })+ .mockRejectedValueOnce(new Error('provider unreachable'));+ const { onRewritten } = renderDrawer(loom);+ await clickRewrite(user);++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('provider unreachable'));+ expect(reformatLoomEpisode).toHaveBeenCalledTimes(2);+ // The selection is cleared up front AND the record re-read afterwards — the+ // failed walk still changed scene text on the server.+ expect(onRewritten).toHaveBeenNthCalledWith(1, { refetch: false });+ expect(onRewritten).toHaveBeenCalledTimes(2);+ expect(screen.queryByText(/Rewriting episode/)).not.toBeInTheDocument();+ });++ it('offers no rewrite at all once every scene is already in the target format', () => {+ renderDrawer(makeLoom([{ id: 'ep-1', title: 'Pilot', nodes: [scene('s1', 'teleplay')] }]));+ expect(screen.queryByRole('button', { name: /^Rewrite/ })).not.toBeInTheDocument();+ expect(screen.getByText(/Every scene you have is already written as teleplay/)).toBeInTheDocument();+ });+});diff --git a/client/src/components/fableloom/loomFormats.js b/client/src/components/fableloom/loomFormats.jsindex ea9bfff0a4..1490aa273c 100644--- a/client/src/components/fableloom/loomFormats.js+++ b/client/src/components/fableloom/loomFormats.js@@ -18,3 +18,25 @@ export const loomFormatHint = (id) => LOOM_FORMATS.find((f) => f.id === id)?.hin/** The one format predicate — display, editor typography, and badges share it. */export const isTeleplayFormat = (id) => id === 'teleplay';++/**+ * Does this scene still need rewriting into `format`? Mirrors the server's own+ * filter (`needsReformat` in `server/services/fableLoom/weave.js`): a scene is+ * pending when it HAS prose and that prose isn't already stamped with the+ * target format. Title-only placeholders are never sent — there is no beat in+ * them to preserve, so the model would invent one.+ */+export const sceneNeedsReformat = (node, format) =>+ !!node?.prose?.trim() && node.format !== format;++/**+ * The episodes a rewrite still has work in, with their pending scene counts.+ * The rewrite is one request per episode, so this is the walk the drawer makes+ * and the denominator of its progress line.+ */+export const episodesNeedingReformat = (loom, format) => (loom?.episodes || [])+ .map((episode) => ({+ episode,+ sceneCount: episode.nodes.filter((n) => sceneNeedsReformat(n, format)).length,+ }))+ .filter((e) => e.sceneCount > 0);diff --git a/client/src/components/fableloom/loomFormats.test.js b/client/src/components/fableloom/loomFormats.test.jsindex ed88e80a3a..920e60de0c 100644--- a/client/src/components/fableloom/loomFormats.test.js+++ b/client/src/components/fableloom/loomFormats.test.js@@ -1,7 +1,9 @@import { describe, it, expect } from 'vitest';import { existsSync, readFileSync } from 'fs';import { dirname, join, resolve } from 'path';-import { LOOM_FORMATS, isTeleplayFormat, loomFormatHint, loomFormatLabel } from './loomFormats.js';+import {+ LOOM_FORMATS, episodesNeedingReformat, isTeleplayFormat, loomFormatHint, loomFormatLabel, sceneNeedsReformat,+} from './loomFormats.js';const SERVER_FORMATS = join('server', 'services', 'fableLoom', 'formats.js');@@ -48,3 +50,30 @@ describe('loomFormats', () => {expect(isTeleplayFormat('teleplay')).toBe(true);});});++describe('reformat pending helpers', () => {+ const loom = {+ episodes: [+ { id: 'ep-1', nodes: [{ prose: 'Written.', format: 'prose' }, { prose: 'Also written.' }] },+ { id: 'ep-2', nodes: [{ prose: 'Converted.', format: 'teleplay' }] },+ { id: 'ep-3', nodes: [{ title: 'Placeholder', prose: ' ' }] },+ ],+ };++ it('counts only scenes with prose that is not already in the target format', () => {+ // A title-only placeholder has no beat to preserve, so it is never sent —+ // the model would invent one and it would land as if authored.+ expect(sceneNeedsReformat({ prose: ' ' }, 'teleplay')).toBe(false);+ expect(sceneNeedsReformat({ prose: 'Written.' }, 'teleplay')).toBe(true);+ expect(sceneNeedsReformat({ prose: 'Written.', format: 'teleplay' }, 'teleplay')).toBe(false);+ expect(sceneNeedsReformat(undefined, 'teleplay')).toBe(false);+ });++ it('lists only the episodes a rewrite still has work in', () => {+ expect(episodesNeedingReformat(loom, 'teleplay').map((e) => [e.episode.id, e.sceneCount]))+ .toEqual([['ep-1', 2]]);+ expect(episodesNeedingReformat(loom, 'prose').map((e) => [e.episode.id, e.sceneCount]))+ .toEqual([['ep-1', 1], ['ep-2', 1]]);+ expect(episodesNeedingReformat(undefined, 'prose')).toEqual([]);+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 2a640b2783..e032b7ebbd 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -102,7 +102,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiMediaJobs.js` | Media generation job tracking + `refineMediaPrompt` / `promptFromMedia` (vision reverse-prompt). || `apiCreativeDirector.js` | Creative Director (video production). || `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). |-| `apiFableLoom.js` | FableLoom branching narratives — loom/episode/scene-node/transition CRUD, deterministic graph validation, and the AI lanes (weave, branch, review, play turns). |+| `apiFableLoom.js` | FableLoom branching narratives — loom/episode/scene-node/transition CRUD, deterministic graph validation, and the AI lanes (weave, branch, review, play turns, per-episode scene reformat). || `apiGames.js` | Game studio records, managed-app binding, reusable sprite/music bindings, deterministic asset-bundle compilation/integrity preflight, and AI feedback history. || `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. || `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). |diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.jsindex 219c5d46d9..7880b43196 100644--- a/client/src/services/apiFableLoom.js+++ b/client/src/services/apiFableLoom.js@@ -75,6 +75,11 @@ export const reviewLoomEpisode = (id, episodeId, body = {}, options = {}) => reqexport const playLoomTurn = (id, episodeId, body, options = {}) => request(episodePath(id, episodeId, '/play'), {method: 'POST', body: JSON.stringify(body), ...options,});-export const reformatLoom = (id, body, options = {}) => request(loomPath(id, '/reformat'), {- method: 'POST', body: JSON.stringify(body), ...options,-});+// One episode per call. The caller walks the episodes it needs rewritten — a+// whole-loom rewrite in one request ran long enough to hit a fetch timeout. The+// server pins the loom to the format once every episode is converted, so an+// interrupted walk never leaves the loom claiming a format its scenes are not in.+export const reformatLoomEpisode = (id, episodeId, body, options = {}) =>+ request(episodePath(id, episodeId, '/reformat'), {+ method: 'POST', body: JSON.stringify(body), ...options,+ });diff --git a/docs/features/fableloom.md b/docs/features/fableloom.mdindex 8b45f9f5f4..539821c4da 100644--- a/docs/features/fableloom.md+++ b/docs/features/fableloom.md@@ -66,10 +66,29 @@ and play-turn narration all follow it, and the reader-facing scene cardsrender a teleplay monospaced.Changing the setting steers *new* generation only. **Story settings → Rewrite-all N scenes** runs `fableloom-reformat-scenes` over every scene of every-episode (in chunks, persisted as each chunk lands, so a mid-run failure keeps-what already succeeded) and re-pins the loom. It rewrites text only: ids,-transitions, endings, and image prompts are untouched.+N scenes** runs `fableloom-reformat-scenes` over the scenes not already in the+target format. It rewrites text only: ids, transitions, endings, and image+prompts are untouched.++The rewrite is **one request per episode** —+`POST /api/fableloom/:id/episodes/:episodeId/reformat`, with the drawer walking+the episodes that still have work and naming the one in flight. A whole-loom+rewrite used to run every provider call behind a single held request (227s on a+13-scene loom, and tens of minutes on a large one), long enough for a proxy or+fetch timeout to kill the response while the server kept writing. Each request+is capped at 20 scenes; a response that stopped there says `capped: true` and+the drawer asks the same episode again, so a long episode is several bounded+requests rather than one open-ended one.++Two properties survive that split:++- **Resumability.** Each chunk of 5 scenes is persisted as it lands and stamped+ with the format it was written in, so a mid-run failure keeps what already+ succeeded and re-running rewrites only what is left.+- **No half-and-half loom.** The loom's `format` pin is written by the *server*,+ and only once no episode has an unconverted scene left — so a browser closed+ mid-walk can't leave the loom claiming a format half its story isn't in.+ Until then the run reports what remains and the drawer says to run it again.## Playing: what costs an LLM calldiff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.jsindex bc15f1d654..1077951b8a 100644--- a/server/routes/fableLoom.js+++ b/server/routes/fableLoom.js@@ -41,7 +41,7 @@ import {getLoom,listLoomSummaries,playTurn,- reformatLoom,+ reformatEpisodeScenes,reviewEpisode,updateEpisode,updateLoom,@@ -174,12 +174,15 @@ router.post('/:id/episodes/:episodeId/play', asyncHandler(async (req, res) => {res.json(await playTurn(req.params.id, req.params.episodeId, input));}));-// Rewrite every scene of every episode into another format (prose ⇄ teleplay)-// and pin the loom to it. Loom-scoped rather than episode-scoped: a story-// half in screenplay and half in prose is never what the author meant.-router.post('/:id/reformat', asyncHandler(async (req, res) => {+// Rewrite ONE episode's scenes into another format (prose ⇄ teleplay). The+// caller walks the episodes; a whole-loom rewrite used to run tens of+// sequential provider calls behind one held request, long enough for a proxy or+// fetch timeout to kill the response mid-run (#4794). The invariant that a+// story is never half screenplay and half prose is kept by the service, which+// pins the loom to the format only once every episode is converted.+router.post('/:id/episodes/:episodeId/reformat', asyncHandler(async (req, res) => {const input = validateRequest(reformatSchema, req.body);- res.json(await reformatLoom(req.params.id, input));+ res.json(await reformatEpisodeScenes(req.params.id, req.params.episodeId, input));}));export default router;diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.jsindex 4bc8689b51..32f8ac668b 100644--- a/server/routes/fableLoom.test.js+++ b/server/routes/fableLoom.test.js@@ -16,7 +16,7 @@ vi.mock('../services/fableLoom/index.js', () => ({getLoom: vi.fn(),listLoomSummaries: vi.fn(async () => []),playTurn: vi.fn(),- reformatLoom: vi.fn(),+ reformatEpisodeScenes: vi.fn(),reviewEpisode: vi.fn(),updateEpisode: vi.fn(),updateLoom: vi.fn(),@@ -206,19 +206,27 @@ describe('FableLoom routes', () => {expect(fableLoom.playTurn).toHaveBeenCalledWith('loom-1', 'ep-1', { nodeId: 'node-1', transitionId: 'tr-1' });});- it('POST reformat validates the target format and forwards it', async () => {+ it('POST reformat is episode-scoped, validates the target format, and forwards it', async () => {const invalid = await request(makeApp())- .post('/api/fableloom/loom-1/reformat')+ .post('/api/fableloom/loom-1/episodes/ep-1/reformat').send({ format: 'haiku' });expect(invalid.status).toBe(400);- expect(fableLoom.reformatLoom).not.toHaveBeenCalled();+ expect(fableLoom.reformatEpisodeScenes).not.toHaveBeenCalled();- fableLoom.reformatLoom.mockResolvedValueOnce({ loom: { id: 'loom-1' }, rewritten: 3 });+ fableLoom.reformatEpisodeScenes.mockResolvedValueOnce({ loom: { id: 'loom-1' }, rewritten: 3 });const ok = await request(makeApp())- .post('/api/fableloom/loom-1/reformat')+ .post('/api/fableloom/loom-1/episodes/ep-1/reformat').send({ format: 'teleplay', providerId: 'claude' });expect(ok.status).toBe(200);- expect(fableLoom.reformatLoom).toHaveBeenCalledWith('loom-1', { format: 'teleplay', providerId: 'claude' });+ expect(fableLoom.reformatEpisodeScenes).toHaveBeenCalledWith('loom-1', 'ep-1', { format: 'teleplay', providerId: 'claude' });++ // The loom-scoped route is gone: one request per episode is the whole point+ // of the change, so a caller still hitting the old path must fail loudly+ // rather than quietly rewriting nothing.+ const legacy = await request(makeApp())+ .post('/api/fableloom/loom-1/reformat')+ .send({ format: 'teleplay' });+ expect(legacy.status).toBe(404);});it('POST play requires a nodeId and message', async () => {diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.mdindex e6d1ad63d7..c0f1a5265f 100644--- a/server/services/fableLoom/README.md+++ b/server/services/fableLoom/README.md@@ -8,7 +8,7 @@ intent to a transition and moves them through the graph until an ending.| Module | Purpose ||---|---|| `records.js` | Sanitizer + CRUD for looms/episodes/nodes; transitions are addressable one at a time (`addNodeTransition` / `updateNodeTransition` / `deleteNodeTransition`) as well as replaceable as a whole array via the node patch; `attachNodeImage` for the media-job hook. |-| `weave.js` | AI ops via `runStagedLLM`: `weaveEpisode` (full graph), `branchNode` (grow paths), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; a tapped path resolves off the graph with NO LLM call), `reformatLoom` (rewrite every scene into another format). |+| `weave.js` | AI ops via `runStagedLLM`: `weaveEpisode` (full graph), `branchNode` (grow paths), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; a tapped path resolves off the graph with NO LLM call), `reformatEpisodeScenes` (rewrite ONE episode's scenes into another format; the loom's format pin lands only once every episode is converted). || `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. || `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). || `db.js` | PostgreSQL leaf I/O. |diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.jsindex 3e99728a1d..af4203e04d 100644--- a/server/services/fableLoom/index.js+++ b/server/services/fableLoom/index.js@@ -28,7 +28,7 @@ export {mapGeneratedGraph,playTurn,publicNode,- reformatLoom,+ reformatEpisodeScenes,reviewEpisode,weaveEpisode,} from './weave.js';diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex 1c16363ac2..bc0cba995c 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -333,92 +333,103 @@ function moveResult(episode, node, transition, { narration = '', resolvedBy, run// Scenes per LLM call. Small enough that one refusal or truncation costs a// handful of scenes rather than the episode, large enough that a 13-scene-// episode is two calls, not thirteen.+// episode is three calls, not thirteen.const REFORMAT_CHUNK = 5;-// Hard ceiling on provider calls per request. The record caps allow 100-// episodes x 200 scenes, which at 5 per call is 4,000 sequential calls behind-// one HTTP request — a spend and timeout hazard nobody asked for. A run that-// hits the ceiling reports what is left, and re-running genuinely finishes the-// job: each scene is stamped with the format it was written in as it lands, so-// the next pass skips what is already converted instead of re-sending it and-// stopping in the same place forever.-const REFORMAT_CHUNKS_MAX = 40;+// Hard ceiling on provider calls per request: 20 scenes. Enough that an+// ordinary episode is one round trip, few enough that a 200-scene episode (the+// record's own cap) can't hold a connection open for the 40 sequential calls it+// would otherwise take. A run that stops here says so with `capped`, and the+// caller simply asks again: each scene is stamped with the format it was written+// in as it lands, so the next pass picks up exactly where this one stopped+// instead of re-sending converted scenes and stalling in the same place forever.+const REFORMAT_CHUNKS_MAX = 4;++// A scene needs rewriting when it HAS prose and that prose isn't already in the+// target format. Title-only placeholders are skipped, not sent: a rewrite+// prompt whose rule is "every beat must survive" has nothing to preserve in an+// empty scene, so the model invents one and it lands on the node as if authored.+const needsReformat = (node, target) => isStr(node.prose) && !!node.prose.trim() && node.format !== target;++/** Scenes across the WHOLE loom still waiting to be rewritten into `target`. */+const unconvertedSceneCount = (loom, target) => loom.episodes.reduce(+ (total, ep) => total + ep.nodes.filter((n) => needsReformat(n, target)).length, 0,+);/**- * Rewrite every scene of every episode into `format` (prose ⇄ teleplay) and- * pin the loom to it, so later weaves/branches/play turns keep generating in- * the same format.+ * Rewrite one episode's scenes into `format` (prose ⇄ teleplay), and pin the+ * loom to that format once — and only once — every episode is converted.+ *+ * Episode-scoped on purpose: rewriting a whole loom in one request meant tens+ * of sequential provider calls behind a single held connection, long enough for+ * a proxy or fetch timeout to kill the response while the server kept writing+ * (#4794). The client walks the episodes and shows which one is in flight; each+ * request is bounded by one episode's scenes.** Each chunk is persisted as it lands: a provider failure halfway through* leaves the already-rewritten scenes rewritten, and re-running finishes the- * job rather than starting over. The loom's format pin is written LAST and only- * once EVERY scene is converted — a loom still holding unconverted scenes must- * not claim a format its story isn't in, or every later weave/branch/play- * generates against a contract that story doesn't follow.+ * job rather than starting over. The format pin is written LAST and only once+ * EVERY scene in the loom is converted — a loom still holding unconverted+ * scenes must not claim a format its story isn't in, or every later+ * weave/branch/play generates against a contract that story doesn't follow.+ * Keeping that check on the server rather than in the client's loop means a+ * browser closed mid-walk can't leave the loom pinned to a format half its+ * scenes are not in.*/-export async function reformatLoom(loomId, { format, providerId, model, effort } = {}) {+export async function reformatEpisodeScenes(loomId, episodeId, { format, providerId, model, effort } = {}) {const target = asLoomFormat(format);const loom = await requireLoom(loomId);+ const episode = findEpisode(loom, episodeId);const canonDigest = await buildCanonDigest(loom);const runIds = [];- // Title-only placeholder scenes are skipped, not sent: a rewrite prompt whose- // rule is "every beat must survive" has nothing to preserve in an empty- // scene, so the model invents one and it lands on the node as if authored.- const pending = loom.episodes.map((episode) => ({- episode,- nodes: episode.nodes.filter((n) => isStr(n.prose) && n.prose.trim() && n.format !== target),- })).filter((e) => e.nodes.length);- const sceneCount = pending.reduce((total, e) => total + e.nodes.length, 0);+ const nodes = episode.nodes.filter((n) => needsReformat(n, target));let rewritten = 0;let chunks = 0;- for (const { episode, nodes } of pending) {- for (let i = 0; i < nodes.length; i += REFORMAT_CHUNK) {- const batch = nodes.slice(i, i + REFORMAT_CHUNK);- if (chunks >= REFORMAT_CHUNKS_MAX) continue;- chunks += 1;- const { content, runId } = await runStagedLLM('fableloom-reformat-scenes', {- // The TARGET format, not the loom's current one: the pin is written- // last, so passing `loom` would assert the source format as fact in- // the same prompt that asks for the target — and would render- // differently on a resumed run than on the first one.- storyContext: storyContext({ ...loom, format: target }, episode),- canonDigest: canonDigest || '(none)',- formatLabel: loomFormatLabel(target),- sceneFormatContract: sceneFormatContract(target),- scenesJson: JSON.stringify(batch.map((n) => ({ id: n.id, title: n.title, prose: n.prose })), null, 2),- }, llmOptions({ providerId, model, effort }, 'fableloom-reformat'));- if (runId) runIds.push(runId);-- // Only ids from THIS batch count. A model that invents an id, echoes a- // typo, or names a scene from another episode writes nothing — counting- // those would report scenes as rewritten that still hold their old prose- // and would satisfy the no-response guard below on a total miss.- const batchIds = new Set(batch.map((n) => n.id));- const byId = new Map((Array.isArray(content?.scenes) ? content.scenes : [])- .filter((sc) => sc && typeof sc === 'object' && isStr(sc.id) && batchIds.has(sc.id)- && isStr(sc.prose) && sc.prose.trim())- .map((sc) => [sc.id, sc]));- if (!byId.size) continue;- await mutateLoom(loomId, (current) => {- const ep = findEpisode(current, episode.id);- for (const sceneNode of ep.nodes) {- const rewrite = byId.get(sceneNode.id);- if (!rewrite) continue;- sceneNode.prose = rewrite.prose;- sceneNode.format = target;- if (isStr(rewrite.title) && rewrite.title.trim()) sceneNode.title = rewrite.title;- }- ep.updatedAt = new Date().toISOString();- return current;- });- rewritten += byId.size;- }+ for (let i = 0; i < nodes.length && chunks < REFORMAT_CHUNKS_MAX; i += REFORMAT_CHUNK) {+ const batch = nodes.slice(i, i + REFORMAT_CHUNK);+ chunks += 1;+ const { content, runId } = await runStagedLLM('fableloom-reformat-scenes', {+ // The TARGET format, not the loom's current one: the pin is written+ // last, so passing `loom` would assert the source format as fact in+ // the same prompt that asks for the target — and would render+ // differently on a resumed run than on the first one.+ storyContext: storyContext({ ...loom, format: target }, episode),+ canonDigest: canonDigest || '(none)',+ formatLabel: loomFormatLabel(target),+ sceneFormatContract: sceneFormatContract(target),+ scenesJson: JSON.stringify(batch.map((n) => ({ id: n.id, title: n.title, prose: n.prose })), null, 2),+ }, llmOptions({ providerId, model, effort }, 'fableloom-reformat'));+ if (runId) runIds.push(runId);++ // Only ids from THIS batch count. A model that invents an id, echoes a+ // typo, or names a scene from another episode writes nothing — counting+ // those would report scenes as rewritten that still hold their old prose+ // and would satisfy the no-response guard below on a total miss.+ const batchIds = new Set(batch.map((n) => n.id));+ const byId = new Map((Array.isArray(content?.scenes) ? content.scenes : [])+ .filter((sc) => sc && typeof sc === 'object' && isStr(sc.id) && batchIds.has(sc.id)+ && isStr(sc.prose) && sc.prose.trim())+ .map((sc) => [sc.id, sc]));+ if (!byId.size) continue;+ await mutateLoom(loomId, (current) => {+ const ep = findEpisode(current, episode.id);+ for (const sceneNode of ep.nodes) {+ const rewrite = byId.get(sceneNode.id);+ if (!rewrite) continue;+ sceneNode.prose = rewrite.prose;+ sceneNode.format = target;+ if (isStr(rewrite.title) && rewrite.title.trim()) sceneNode.title = rewrite.title;+ }+ ep.updatedAt = new Date().toISOString();+ return current;+ });+ rewritten += byId.size;}- // A loom with nothing to rewrite is a no-op, not a failure — the pin is still- // the point. Only a loom that HAD scenes and got none back is a bad response.- if (sceneCount && !rewritten) throw aiShapeError('The model returned no rewritten scenes');+ // An episode with nothing to rewrite is a no-op, not a failure — the client+ // walks every episode, and the pin below is still the point. Only an episode+ // that HAD scenes and got none back is a bad response.+ if (nodes.length && !rewritten) throw aiShapeError('The model returned no rewritten scenes');// Counted off the RECORD rather than accumulated in the loop, because scenes// go unconverted for two unrelated reasons: the per-request ceiling stopped@@ -426,11 +437,18 @@ export async function reformatLoom(loomId, { format, providerId, model, effort }// batch). Tracking only the first would report a partial rewrite as complete// and pin the loom to a format some of its scenes are not in.const after = await getLoom(loomId);- const remaining = after.episodes.reduce((total, ep) => total- + ep.nodes.filter((n) => isStr(n.prose) && n.prose.trim() && n.format !== target).length, 0);+ const episodeRemaining = findEpisode(after, episodeId).nodes.filter((n) => needsReformat(n, target)).length;+ const remaining = unconvertedSceneCount(after, target);+ // `capped` separates the two reasons an episode can come back unfinished: this+ // run hit its ceiling with scenes it never SENT (ask again and it continues+ // from there), or the model dropped scenes it was given (asking again just+ // re-sends them, and a second refusal is an error, not progress). Only the+ // first earns an automatic follow-up request — and since a capped run always+ // rewrote at least one scene, following it up strictly makes progress.+ const capped = nodes.length > chunks * REFORMAT_CHUNK;// Only a fully-converted loom gets the pin.const updated = remaining? after: await mutateLoom(loomId, (current) => ({ ...current, format: target }));- return { loom: updated, format: target, rewritten, remaining, runIds };+ return { loom: updated, format: target, rewritten, episodeRemaining, remaining, capped, runIds };}diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.jsindex 31e0824fbd..87304ab4fd 100644--- a/server/services/fableLoom/weave.test.js+++ b/server/services/fableLoom/weave.test.js@@ -25,7 +25,7 @@ vi.mock('../pipeline/series.js', () => ({ getSeries: getSeriesMock }));const { createLoom, addEpisode, addNode, mutateLoom, updateLoom, updateNode, getLoom } = await import('./records.js');const { _resetFableLoomBackend } = await import('./store.js');const {- branchNode, buildCanonDigest, mapGeneratedGraph, playTurn, reformatLoom, reviewEpisode, weaveEpisode,+ branchNode, buildCanonDigest, mapGeneratedGraph, playTurn, reformatEpisodeScenes, reviewEpisode, weaveEpisode,} = await import('./weave.js');beforeEach(() => {@@ -286,7 +286,7 @@ describe('playTurn', () => {});});-describe('reformatLoom', () => {+describe('reformatEpisodeScenes', () => {const proseSetup = async () => {const { loomId, episodeId } = await setup();let updated = await addNode(loomId, episodeId, { title: 'The Gate', prose: 'You stand before it.' });@@ -297,7 +297,7 @@ describe('reformatLoom', () => {};it('rewrites every returned scene, pins the format, and leaves the graph alone', async () => {- const { loomId, gateId, insideId } = await proseSetup();+ const { loomId, episodeId, gateId, insideId } = await proseSetup();runStagedLLM.mockImplementation(async (stage, variables) => ({content: {scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: `INT. GATE - NIGHT\n\n${sc.prose}` })),@@ -305,7 +305,7 @@ describe('reformatLoom', () => {runId: 'run-1',}));- const result = await reformatLoom(loomId, { format: 'teleplay' });+ const result = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });expect(result).toMatchObject({ format: 'teleplay', rewritten: 2 });expect(result.loom.format).toBe('teleplay');const nodes = result.loom.episodes[0].nodes;@@ -319,13 +319,13 @@ describe('reformatLoom', () => {});it('counts only scenes it actually wrote, not every id the model echoed back', async () => {- const { loomId, gateId, insideId } = await proseSetup();+ const { loomId, episodeId, gateId, insideId } = await proseSetup();// Ids that are not in the batch: invented, or from another episode. The// write applies none of them, so neither may be counted as rewritten.runStagedLLM.mockResolvedValue({content: { scenes: [{ id: 'node-invented', prose: 'INT. NOWHERE' }, { id: gateId, prose: 'INT. GATE' }] },});- const result = await reformatLoom(loomId, { format: 'teleplay' });+ const result = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });expect(result.rewritten).toBe(1);const nodes = result.loom.episodes[0].nodes;expect(nodes.find((n) => n.id === gateId).prose).toBe('INT. GATE');@@ -333,15 +333,15 @@ describe('reformatLoom', () => {});it('leaves the format pin alone when the rewrite never landed a scene', async () => {- const { loomId } = await proseSetup();+ const { loomId, episodeId } = await proseSetup();runStagedLLM.mockRejectedValue(new Error('provider unreachable'));- await expect(reformatLoom(loomId, { format: 'teleplay' })).rejects.toThrow('provider unreachable');+ await expect(reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' })).rejects.toThrow('provider unreachable');// Pinning before the rewrite would leave every later weave/branch/play// generating teleplay against a story still written as prose.expect((await getLoom(loomId)).format).toBe('prose');runStagedLLM.mockReset().mockResolvedValue({ content: { scenes: [] } });- await expect(reformatLoom(loomId, { format: 'teleplay' })).rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });+ await expect(reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' })).rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });expect((await getLoom(loomId)).format).toBe('prose');});@@ -357,7 +357,7 @@ describe('reformatLoom', () => {if (call > 1) throw new Error('provider died mid-run');return { content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: `INT. ${sc.prose}` })) } };});- await expect(reformatLoom(loomId, { format: 'teleplay' })).rejects.toThrow('provider died mid-run');+ await expect(reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' })).rejects.toThrow('provider died mid-run');const nodes = (await getLoom(loomId)).episodes[0].nodes;expect(nodes.slice(0, 5).every((n) => n.prose.startsWith('INT. '))).toBe(true);@@ -372,57 +372,105 @@ describe('reformatLoom', () => {content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: 'INT. SOMEWHERE' })) },}));- const result = await reformatLoom(loomId, { format: 'teleplay' });+ const result = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });expect(result.rewritten).toBe(1);const sent = JSON.parse(runStagedLLM.mock.calls[0][1].scenesJson);expect(sent).toHaveLength(1);expect(result.loom.episodes[0].nodes.find((n) => n.title.startsWith('Placeholder')).prose).toBe('');});- it('stops at the per-request ceiling and genuinely finishes on the next run', async () => {+ it('stops at the per-request ceiling, flags it, and continues where it stopped', async () => {const { loomId, episodeId } = await setup();- // The ceiling is 40 chunks x 5 scenes = 200, and NODES_MAX caps ONE episode- // at 200 — so only a multi-episode loom can reach it. Two episodes of 105- // scenes = 42 chunks: the first run stops 2 chunks short.- const withEp2 = await addEpisode(loomId, { title: 'Two' });- const episode2Id = withEp2.episodes[1].id;+ // The ceiling is 4 chunks x 5 scenes = 20 per request. 25 scenes takes two+ // requests: the first sends 20 and reports 5 it never got to.await mutateLoom(loomId, (current) => {- for (const [index, epId] of [episodeId, episode2Id].entries()) {- const ep = current.episodes.find((e) => e.id === epId);- ep.nodes = Array.from({ length: 105 }, (_, i) => ({- id: `node-ceiling-${index}-${i}`, title: `Scene ${i}`, prose: `Prose ${index}-${i}.`, transitions: [],- }));- }+ const ep = current.episodes.find((e) => e.id === episodeId);+ ep.nodes = Array.from({ length: 25 }, (_, i) => ({+ id: `node-ceiling-${i}`, title: `Scene ${i}`, prose: `Prose ${i}.`, transitions: [],+ }));return current;});runStagedLLM.mockImplementation(async (stage, variables) => ({content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: `INT. ${sc.prose}` })) },}));- const first = await reformatLoom(loomId, { format: 'teleplay' });- expect(first).toMatchObject({ rewritten: 200, remaining: 10 });+ const first = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });+ expect(runStagedLLM.mock.calls).toHaveLength(4);+ expect(first).toMatchObject({ rewritten: 20, episodeRemaining: 5, remaining: 5, capped: true });// The loom is NOT pinned yet — 5 scenes are still prose.expect(first.loom.format).toBe('prose');- const callsAfterFirst = runStagedLLM.mock.calls.length;- const second = await reformatLoom(loomId, { format: 'teleplay' });- // Only the 2 leftover chunks are re-sent; the 200 already converted are skipped.- expect(runStagedLLM.mock.calls.length - callsAfterFirst).toBe(2);- expect(second).toMatchObject({ rewritten: 10, remaining: 0 });+ const second = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });+ // Only the one leftover chunk is re-sent; the 20 already converted are skipped.+ expect(runStagedLLM.mock.calls).toHaveLength(5);+ expect(second).toMatchObject({ rewritten: 5, episodeRemaining: 0, remaining: 0, capped: false });expect(second.loom.format).toBe('teleplay');const allNodes = second.loom.episodes.flatMap((e) => e.nodes);- expect(allNodes).toHaveLength(210);+ expect(allNodes).toHaveLength(25);expect(allNodes.every((n) => n.prose.startsWith('INT. '))).toBe(true);expect(allNodes.every((n) => n.format === 'teleplay')).toBe(true);});+ it('does not flag a run as capped when the model, not the ceiling, left scenes behind', async () => {+ const { loomId, episodeId, gateId } = await proseSetup();+ // One of two scenes comes back. Nothing went unsent, so re-requesting would+ // only re-send a refusal — the caller must NOT loop on this.+ runStagedLLM.mockResolvedValue({ content: { scenes: [{ id: gateId, prose: 'INT. GATE' }] } });+ const result = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });+ expect(result).toMatchObject({ rewritten: 1, episodeRemaining: 1, capped: false });+ });++ it('holds the loom pin until EVERY episode is converted, not just the one it rewrote', async () => {+ const { loomId, episodeId } = await proseSetup();+ const withEp2 = await addEpisode(loomId, { title: 'Two' });+ const episode2Id = withEp2.episodes[1].id;+ await addNode(loomId, episode2Id, { title: 'Elsewhere', prose: 'Rain on the roof.' });+ runStagedLLM.mockImplementation(async (stage, variables) => ({+ content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: `INT. ${sc.prose}` })) },+ }));++ // Episode one is fully converted — but the loom still holds a prose scene in+ // episode two, and pinning here would point every later weave/branch/play at+ // a contract that scene isn't written in.+ const first = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });+ expect(first).toMatchObject({ rewritten: 2, episodeRemaining: 0, remaining: 1 });+ expect(first.loom.format).toBe('prose');++ const second = await reformatEpisodeScenes(loomId, episode2Id, { format: 'teleplay' });+ expect(second).toMatchObject({ rewritten: 1, episodeRemaining: 0, remaining: 0 });+ expect(second.loom.format).toBe('teleplay');+ });++ it('is a no-op on an episode with nothing left to convert, and still pins the loom', async () => {+ const { loomId, episodeId } = await proseSetup();+ runStagedLLM.mockImplementation(async (stage, variables) => ({+ content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: `INT. ${sc.prose}` })) },+ }));+ await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });+ const callsAfterFirst = runStagedLLM.mock.calls.length;++ // The caller walks every episode; one already converted must not cost a+ // provider call, and must not be mistaken for "the model returned nothing".+ const again = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });+ expect(runStagedLLM.mock.calls).toHaveLength(callsAfterFirst);+ expect(again).toMatchObject({ rewritten: 0, remaining: 0, capped: false });+ expect(again.loom.format).toBe('teleplay');+ });++ it('404s on an episode that is not in the loom', async () => {+ const { loomId } = await proseSetup();+ await expect(reformatEpisodeScenes(loomId, 'ep-not-here', { format: 'teleplay' }))+ .rejects.toMatchObject({ status: 404 });+ expect(runStagedLLM).not.toHaveBeenCalled();+ });+it('reports scenes the model dropped as remaining, and holds the pin back', async () => {- const { loomId, gateId, insideId } = await proseSetup();+ const { loomId, episodeId, gateId, insideId } = await proseSetup();// The model returns one of the two scenes it was given. The run is under// the chunk ceiling, so nothing but the dropped scene is left over.runStagedLLM.mockResolvedValue({ content: { scenes: [{ id: gateId, prose: 'INT. GATE' }] } });- const result = await reformatLoom(loomId, { format: 'teleplay' });+ const result = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });expect(result).toMatchObject({ rewritten: 1, remaining: 1 });// Claiming teleplay here would point every later weave/branch/play at a// contract the untouched scene isn't written in.@@ -431,17 +479,17 @@ describe('reformatLoom', () => {// Finishing the job pins it.runStagedLLM.mockResolvedValue({ content: { scenes: [{ id: insideId, prose: 'INT. INSIDE' }] } });- const done = await reformatLoom(loomId, { format: 'teleplay' });+ const done = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });expect(done).toMatchObject({ rewritten: 1, remaining: 0 });expect(done.loom.format).toBe('teleplay');});it('asks the model for the TARGET format, not the one the loom still holds', async () => {- const { loomId } = await proseSetup();+ const { loomId, episodeId } = await proseSetup();runStagedLLM.mockImplementation(async (stage, variables) => ({content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: 'INT. GATE' })) },}));- await reformatLoom(loomId, { format: 'teleplay' });+ await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });const [, variables] = runStagedLLM.mock.calls[0];// Asserting the source format here as fact would contradict the template's// own "Target format" heading in the same prompt.@@ -450,14 +498,14 @@ describe('reformatLoom', () => {});it('ignores scenes the model dropped or blanked, and fails when it returns none', async () => {- const { loomId, gateId, insideId } = await proseSetup();+ const { loomId, episodeId, gateId, insideId } = await proseSetup();runStagedLLM.mockResolvedValue({ content: { scenes: [{ id: gateId, prose: 'INT. GATE' }, { id: insideId, prose: ' ' }] } });- const kept = await reformatLoom(loomId, { format: 'teleplay' });+ const kept = await reformatEpisodeScenes(loomId, episodeId, { format: 'teleplay' });expect(kept.rewritten).toBe(1);expect(kept.loom.episodes[0].nodes.find((n) => n.id === insideId).prose).toBe('Torchlight.');runStagedLLM.mockResolvedValue({ content: { scenes: [] } });- await expect(reformatLoom(loomId, { format: 'prose' }))+ await expect(reformatEpisodeScenes(loomId, episodeId, { format: 'prose' })).rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });});});