Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (local gate): count only scenes actually rewritten, pin format last

[._.]/ Adam Eivy49581ac8211b
diff --git a/client/src/components/fableloom/LoomPlayPanel.jsx b/client/src/components/fableloom/LoomPlayPanel.jsx
index 1c378af1bc..1df717de62 100644
--- a/client/src/components/fableloom/LoomPlayPanel.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.jsx
@@ -88,7 +88,13 @@ export default function LoomPlayPanel({ loom, episode }) {
setScene(result.node);
additions.push({ role: 'scene', node: result.node });
}
- if (additions.length) setTranscript((prev) => [...prev, ...additions]);
+ // A turn that moves nowhere and says nothing would read as the app
+ // ignoring the reader. It happens for real: a path whose target scene the
+ // author deleted stays on the graph (the editor surfaces it as an error
+ // rather than silently rewriting edges), and the server answers 'stay'
+ // with no narration.
+ if (!additions.length) additions.push({ role: 'narrator', text: 'Nothing comes of it.' });
+ setTranscript((prev) => [...prev, ...additions]);
}, { errorMessage: 'The narrator lost the thread — try again' });
// Tapping a path: the reader already named the transition, so the turn
diff --git a/client/src/components/fableloom/LoomPlayPanel.test.jsx b/client/src/components/fableloom/LoomPlayPanel.test.jsx
index 76a78d7107..98b813d254 100644
--- a/client/src/components/fableloom/LoomPlayPanel.test.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.test.jsx
@@ -97,7 +97,25 @@ describe('LoomPlayPanel', () => {
await waitFor(() => expect(playLoomTurn).toHaveBeenCalledTimes(2));
const [, , payload] = playLoomTurn.mock.calls[1];
expect(payload.nodeId).toBe('n2');
- expect(payload.transcript.every((t) => t.role === 'reader' || t.role === 'narrator')).toBe(true);
- expect(payload.transcript.every((t) => typeof t.text === 'string')).toBe(true);
+ // Length first: `every()` is vacuously true on an empty array, so a filter
+ // that dropped EVERY turn would pass the role/text assertions below.
+ expect(payload.transcript).toHaveLength(3);
+ expect(payload.transcript).toEqual([
+ { role: 'reader', text: 'go in' },
+ { role: 'narrator', text: 'You step through.' },
+ { role: 'reader', text: 'look around' },
+ ]);
+ });
+
+ it('never leaves a turn silent when the server moves nowhere and says nothing', async () => {
+ const user = userEvent.setup();
+ // A path whose target scene the author deleted: the edge is deliberately
+ // kept on the graph, and the server answers stay-with-no-narration.
+ playLoomTurn.mockResolvedValue({ action: 'stay', narration: '', ended: false });
+ render(<LoomPlayPanel loom={loom} episode={episode} />);
+ await user.click(screen.getByRole('button', { name: 'Take path: enter the gate' }));
+
+ await waitFor(() => expect(playLoomTurn).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(screen.getByText('Nothing comes of it.')).toBeInTheDocument());
});
});
diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsx
index 37d752836b..c561666b51 100644
--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx
+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx
@@ -26,7 +26,7 @@ import { reformatLoom, updateLoom } from '../../services/api';
import { fieldClass, labelClass } from './fieldStyles';
import { LOOM_FORMATS, loomFormatHint, loomFormatLabel } from './loomFormats';
-export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate }) {
+export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate, onRewritten }) {
const { providers } = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
const format = loom.format || 'prose';
@@ -48,10 +48,17 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate }
playSettings: { providerId: play.providerId ?? null, model: play.model ?? null, effort: play.effort ?? null, ...changes },
});
+ // `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 () => {
- const result = await reformatLoom(loom.id, { format }, { silent: true });
+ const result = await reformatLoom(loom.id, { format }, { silent: true })
+ .finally(() => onRewritten?.());
onLoomUpdate(result.loom);
- toast.success(`Rewrote ${result.rewritten} scene${result.rewritten === 1 ? '' : 's'} as ${loomFormatLabel(format).toLowerCase()}`);
+ 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()}`);
}, { errorMessage: 'The rewrite failed' });
return (
@@ -104,6 +111,8 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate }
onEffortChange={(effort) => savePlay({ effort: effort || null })}
label="Provider"
layout="stacked"
+ disabled={saving}
+ modelDisabled={saving}
emptyProviderOption="Default (whatever the play stage uses)"
emptyModelOption="Default model"
alwaysShowModel={!!play.providerId}
diff --git a/client/src/lib/loomLayout.js b/client/src/lib/loomLayout.js
index 82978a3dee..ce0924497f 100644
--- a/client/src/lib/loomLayout.js
+++ b/client/src/lib/loomLayout.js
@@ -129,9 +129,13 @@ export function layoutLoomGraph(episode) {
cardBottom = Math.max(cardBottom, y + LOOM_NODE_H);
}
const edges = routeLoomEdges(nodes, positions, cardBottom);
+ // BOTH extents come from the edges too: a self-loop bows past the card's
+ // right side and its label sits further right still, and the SVG root clips
+ // at these numbers — the scrolling wrapper can't recover what the viewBox cut.
let height = cardBottom + MARGIN;
for (const edge of edges) {
height = Math.max(height, edge.maxY + MARGIN);
+ width = Math.max(width, edge.maxX + MARGIN);
}
return { positions, edges, width: Math.max(width, 400), height: Math.max(height, 240) };
}
@@ -221,6 +225,7 @@ export function placeEdgeLabels(edges) {
}
edge.labelY = y;
edge.maxY = Math.max(edge.maxY, y);
+ edge.maxX = Math.max(edge.maxX, edge.labelX + half);
placed.push({ x: edge.labelX, y, half });
}
return edges;
@@ -245,6 +250,7 @@ export function loomEdgePath(from, to, options = {}) {
d: `M ${x} ${y - 24} C ${x + 64} ${y - 44}, ${x + 64} ${y + 44}, ${x} ${y + 24}`,
labelX: x + 46,
labelY: y,
+ maxX: x + 64,
maxY: from.y + LOOM_NODE_H,
};
}
@@ -258,6 +264,7 @@ export function loomEdgePath(from, to, options = {}) {
d: `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2} ${y2}`,
labelX: (x1 + x2) / 2,
labelY: (y1 + y2) / 2,
+ maxX: Math.max(x1, x2),
maxY: Math.max(y1, y2),
};
}
@@ -271,6 +278,7 @@ export function loomEdgePath(from, to, options = {}) {
labelX: (x1 + x2) / 2,
// Bottom of the cubic at t=0.5, where the run is flattest.
labelY: (y1 + y2 + 6 * lane) / 8,
+ maxX: Math.max(x1, x2),
maxY: lane,
};
}
diff --git a/client/src/lib/loomLayout.test.js b/client/src/lib/loomLayout.test.js
index a2e40eaeea..6f69433136 100644
--- a/client/src/lib/loomLayout.test.js
+++ b/client/src/lib/loomLayout.test.js
@@ -34,20 +34,25 @@ describe('loomGraphLayers', () => {
});
it('reorders a layer toward its parents so forward edges stop crossing', () => {
- // a → x, b → y discovered as [y, x]: barycenter pulls x above y to match
- // the parent order, which is the crossing-free arrangement.
+ // `p` (row 0) reaches a and b; `r` (row 2) and `s` (row 3) also reach a.
+ // BFS discovers [a, b] because p's transitions come first — but a's mean
+ // parent row is (0+2+3)/3 = 1.67 against b's 0, so the crossing-free order
+ // is [b, a]. A plain BFS layering CANNOT produce that, which is what makes
+ // this fixture a real test of the barycenter pass rather than of BFS.
const layers = loomGraphLayers({
startNodeId: 'root',
nodes: [
- { id: 'root', transitions: [tr('t1', 'a'), tr('t2', 'b')] },
- { id: 'a', transitions: [tr('t3', 'x')] },
- { id: 'b', transitions: [tr('t4', 'y')] },
- { id: 'y', transitions: [] },
- { id: 'x', transitions: [] },
+ { id: 'root', transitions: [tr('t1', 'p'), tr('t2', 'q'), tr('t3', 'r'), tr('t4', 's')] },
+ { id: 'p', transitions: [tr('t5', 'a'), tr('t6', 'b')] },
+ { id: 'q', transitions: [] },
+ { id: 'r', transitions: [tr('t7', 'a')] },
+ { id: 's', transitions: [tr('t8', 'a')] },
+ { id: 'a', transitions: [] },
+ { id: 'b', transitions: [] },
],
});
- expect(layers[1]).toEqual(['a', 'b']);
- expect(layers[2]).toEqual(['x', 'y']);
+ expect(layers[1]).toEqual(['p', 'q', 'r', 's']);
+ expect(layers[2]).toEqual(['b', 'a']);
});
});
@@ -85,6 +90,18 @@ describe('layoutLoomGraph', () => {
expect(height).toBeGreaterThan(back.maxY);
});
+ it('grows the canvas past a self-loop and its label, not just the cards', () => {
+ const ep = episode();
+ ep.nodes[3].transitions = [{ id: 't-self', targetNodeId: 'n4', intent: 'wait here quietly for now' }];
+ const { edges, width, positions } = layoutLoomGraph(ep);
+ const loop = edges.find((e) => e.id === 't-self');
+ // The SVG root clips at `width` — the scrolling wrapper can't recover what
+ // the viewport cut, so the extent has to include the bow AND the label.
+ expect(loop.maxX).toBeGreaterThan(positions.n4.x + LOOM_NODE_W);
+ expect(width).toBeGreaterThan(loop.maxX);
+ expect(width).toBeGreaterThan(loop.labelX);
+ });
+
it('drops a transition whose target no longer exists', () => {
const ep = episode();
ep.nodes[1].transitions.push(tr('t-dangling', 'gone'));
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 1bd93d5a48..02143d9035 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -78,6 +78,16 @@ export default function FableLoomStory() {
}
};
+ // A rewrite changes scene text server-side (per chunk, so even a failed run
+ // moved some). Re-read the record and drop the scene selection: an open
+ // scene editor still holds the pre-rewrite text and would write it back on
+ // its next blur-save.
+ const handleRewritten = async () => {
+ const fresh = await getLoom(loomId).catch(() => null);
+ if (fresh) setLoom(fresh);
+ if (nodeId) navigate(episodePath(episodeId, null) + (playOpen ? '?play=1' : ''));
+ };
+
const handleAddNode = async () => {
const updated = await addLoomNode(loomId, episode.id, { title: 'New scene' }).catch(() => null);
if (updated) {
@@ -289,6 +299,7 @@ export default function FableLoomStory() {
onClose={() => setSettingsOpen(false)}
loom={loom}
onLoomUpdate={setLoom}
+ onRewritten={handleRewritten}
/>
{episode && (
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
index 9457ef6b4f..321692b71a 100644
--- a/server/lib/fableLoomValidation.js
+++ b/server/lib/fableLoomValidation.js
@@ -37,6 +37,7 @@ export const loomCreateSchema = z.object({
premise: premise.optional(),
styleNotes: styleNotes.optional(),
format: format.optional(),
+ playSettings: playSettings.optional(),
universeId: refId.optional(),
seriesId: refId.optional(),
});
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
index 88bbe0c7c9..7873c59e5a 100644
--- a/server/lib/promptStageCallSites.generated.json
+++ b/server/lib/promptStageCallSites.generated.json
@@ -12,6 +12,7 @@
"server/services/brain.js"
],
"catalog-ideas-scenes-concepts": [
+ "server/lib/creativeLatitude.js",
"server/services/catalogExtraction.js"
],
"cd-evaluate": [
@@ -58,6 +59,7 @@
"server/services/importer.js"
],
"manuscript-reformat": [
+ "server/lib/creativeLatitude.js",
"server/services/pipeline/manuscriptFix.js"
],
"memory-evaluate": [
@@ -67,6 +69,7 @@
"server/services/modelPersonality.js"
],
"model-personality-profile": [
+ "server/lib/creativeLatitude.js",
"server/services/modelPersonality.js"
],
"multi-turn-consistency-scorer": [
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index 4a8c9b8342..80b260edbf 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -200,7 +200,7 @@ export async function getLoom(id) {
return sanitizeLoom(await readRaw(id));
}
-export async function createLoom({ name, logline, premise, styleNotes, format, universeId, seriesId } = {}) {
+export async function createLoom({ name, logline, premise, styleNotes, format, playSettings, universeId, seriesId } = {}) {
const now = new Date().toISOString();
await assertRefsExist({ universeId: nullableRef(universeId), seriesId: nullableRef(seriesId) });
const loom = sanitizeLoom({
@@ -210,6 +210,7 @@ export async function createLoom({ name, logline, premise, styleNotes, format, u
premise,
styleNotes,
format,
+ playSettings,
universeId,
seriesId,
episodes: [],
diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.js
index 35c9dc9857..15671b630f 100644
--- a/server/services/fableLoom/records.test.js
+++ b/server/services/fableLoom/records.test.js
@@ -144,6 +144,24 @@ describe('loom CRUD', () => {
});
});
+describe('format 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 } });
+ expect(loom.format).toBe('teleplay');
+ expect(loom.playSettings).toEqual({ providerId: 'claude', model: 'opus', effort: null });
+
+ // 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 });
+
+ const cleared = await updateLoom(loom.id, { playSettings: null });
+ expect(cleared.playSettings).toBeNull();
+ expect(cleared.format).toBe('teleplay');
+ });
+});
+
describe('listLoomSummaries', () => {
it('projects counts without the episode graphs', async () => {
const loom = await makeLoom({ logline: 'A crown that remembers.' });
diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.js
index db81197e46..64ff1b3804 100644
--- a/server/services/fableLoom/weave.js
+++ b/server/services/fableLoom/weave.js
@@ -333,6 +333,12 @@ function moveResult(episode, node, transition, { narration = '', resolvedBy, run
// handful of scenes rather than the episode, large enough that a 13-scene
// episode is two 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; re-running finishes the job, because
+// scenes already rewritten are skipped as no-ops by the next pass.
+const REFORMAT_CHUNKS_MAX = 40;
/**
* Rewrite every scene of every episode into `format` (prose ⇄ teleplay) and
@@ -341,22 +347,36 @@ const REFORMAT_CHUNK = 5;
*
* 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.
+ * job rather than starting over. The format pin is written LAST — a run that
+ * rewrote nothing must not leave the loom claiming a format its scenes aren't
+ * in, or every later weave/branch/play generates against a contract the story
+ * doesn't follow.
*/
export async function reformatLoom(loomId, { format, providerId, model, effort } = {}) {
const target = asLoomFormat(format);
- // Pin first: the scenes are rewritten INTO this format, so a run that dies
- // halfway leaves the loom already describing what its rewritten scenes are —
- // and it saves a second full-record round-trip at the end.
- const loom = await mutateLoom(loomId, (current) => ({ ...current, format: target }));
+ const loom = await requireLoom(loomId);
const canonDigest = await buildCanonDigest(loom);
const runIds = [];
- const sceneCount = loom.episodes.reduce((total, ep) => total + ep.nodes.length, 0);
+ // 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()),
+ })).filter((e) => e.nodes.length);
+ const sceneCount = pending.reduce((total, e) => total + e.nodes.length, 0);
let rewritten = 0;
-
- for (const episode of loom.episodes) {
- for (let i = 0; i < episode.nodes.length; i += REFORMAT_CHUNK) {
- const batch = episode.nodes.slice(i, i + REFORMAT_CHUNK);
+ let chunks = 0;
+ let remaining = 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) {
+ remaining += batch.length;
+ continue;
+ }
+ chunks += 1;
const { content, runId } = await runStagedLLM('fableloom-reformat-scenes', {
storyContext: storyContext(loom, episode),
canonDigest: canonDigest || '(none)',
@@ -366,8 +386,14 @@ export async function reformatLoom(loomId, { format, providerId, model, effort }
}, 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) && isStr(sc.prose) && sc.prose.trim())
+ .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) => {
@@ -385,9 +411,9 @@ export async function reformatLoom(loomId, { format, providerId, model, effort }
}
}
- // A loom with nothing authored yet is a no-op, not a failure — the pin is
- // still the point. Only a loom that HAD scenes and got none back is a bad
- // response worth surfacing.
+ // 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');
- return { loom: await getLoom(loomId), format: target, rewritten, runIds };
+ const updated = await mutateLoom(loomId, (current) => ({ ...current, format: target }));
+ return { loom: updated, format: target, rewritten, remaining, runIds };
}
diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.js
index 557a91ac36..46a61a241b 100644
--- a/server/services/fableLoom/weave.test.js
+++ b/server/services/fableLoom/weave.test.js
@@ -267,6 +267,12 @@ describe('playTurn', () => {
expect(runStagedLLM.mock.calls[2][2]).toMatchObject({
providerOverride: 'claude', modelOverride: 'opus', effortOverride: 'high',
});
+
+ // A per-call model beats the pinned one outright.
+ await playTurn(loomId, episodeId, { nodeId: gate.id, message: 'look around', model: 'sonnet' });
+ expect(runStagedLLM.mock.calls[3][2]).toMatchObject({
+ providerOverride: 'claude', modelOverride: 'sonnet', effortOverride: 'high',
+ });
});
it("renders the loom's format into the narration contract", async () => {
@@ -312,6 +318,67 @@ describe('reformatLoom', () => {
expect(variables.sceneFormatContract).toContain('slugline');
});
+ it('counts only scenes it actually wrote, not every id the model echoed back', async () => {
+ const { loomId, 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' });
+ expect(result.rewritten).toBe(1);
+ const nodes = result.loom.episodes[0].nodes;
+ expect(nodes.find((n) => n.id === gateId).prose).toBe('INT. GATE');
+ expect(nodes.find((n) => n.id === insideId).prose).toBe('Torchlight.');
+ });
+
+ it('leaves the format pin alone when the rewrite never landed a scene', async () => {
+ const { loomId } = await proseSetup();
+ runStagedLLM.mockRejectedValue(new Error('provider unreachable'));
+ await expect(reformatLoom(loomId, { 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' });
+ expect((await getLoom(loomId)).format).toBe('prose');
+ });
+
+ it('persists each chunk as it lands, so a later failure keeps the earlier work', async () => {
+ const { loomId, episodeId } = await setup();
+ // Six scenes = two chunks; the second one fails.
+ for (let i = 0; i < 6; i += 1) {
+ await addNode(loomId, episodeId, { title: `Scene ${i}`, prose: `Prose ${i}.` });
+ }
+ let call = 0;
+ runStagedLLM.mockImplementation(async (stage, variables) => {
+ call += 1;
+ 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');
+
+ const nodes = (await getLoom(loomId)).episodes[0].nodes;
+ expect(nodes.slice(0, 5).every((n) => n.prose.startsWith('INT. '))).toBe(true);
+ expect(nodes[5].prose).toBe('Prose 5.');
+ });
+
+ it('skips title-only scenes rather than asking the model to invent them', async () => {
+ const { loomId, episodeId } = await setup();
+ await addNode(loomId, episodeId, { title: 'Written', prose: 'You stand before it.' });
+ await addNode(loomId, episodeId, { title: 'Placeholder with no prose yet' });
+ runStagedLLM.mockImplementation(async (stage, variables) => ({
+ content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: 'INT. SOMEWHERE' })) },
+ }));
+
+ const result = await reformatLoom(loomId, { 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('ignores scenes the model dropped or blanked, and fails when it returns none', async () => {
const { loomId, gateId, insideId } = await proseSetup();
runStagedLLM.mockResolvedValue({ content: { scenes: [{ id: gateId, prose: 'INT. GATE' }, { id: insideId, prose: ' ' }] } });