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

feat(writers-room): setting/world bible + bibles fed back into Adapt

Adam Eivy8ad9b8ebe489
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9a6f7252b3..1d20b2329f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Writers Room — setting / world bible (`Refresh settings`) + bibles fed back into Adapt for cross-scene continuity.** New analysis kind `settings` extracts a per-location bible from prose: each entry keyed by screenplay slugline (`INT. CURRY OCITY — NIGHT`) with `description`, `palette`, `era`, `weather`, `recurringDetails`, plus prose evidence + missing-fields hints. Same merge semantics as the character bible — re-runs preserve user edits, only fill blanks, and add new locations. New stage `writers-room-settings` (md prompt + stage-config seed); new service `server/services/writersRoom/settings.js`; new routes `GET/POST /api/writers-room/works/:id/settings`, `PATCH/DELETE /api/writers-room/works/:id/settings/:settingId`; new `SettingsBible.jsx` drawer in WorkEditor with create/edit/delete; new `Refresh settings` menu item. Sluglines normalize identically on client + server (uppercase, em-dash → space, punctuation stripped) so `INT. KITCHEN — NIGHT` and `INT KITCHEN - NIGHT` resolve to the same entry. The script (Adapt) prompt now also receives both bibles as variables (`existingCharactersJson`, `existingSettingsJson`) and is instructed to (a) cite canonical character `physicalDescription` rather than re-improvising and (b) reuse the bible's slugline string verbatim so the storyboard pipeline auto-matches. SceneCard's image-prompt composition now layers the matched setting between world-style and characters: `{worldStyle} . {workTitle} . {setting.description} {setting.palette} {setting.recurring} . Featuring — {chars} . {scene.visualPrompt}` (priority order: visualPrompt always survives, then setting baseline, then characters drop one-by-one to fit the 1900-char budget). End-to-end verified — gemini-2.5-pro extracted 5 locations from a 4,800-word draft in 66s, merged with the user-edited entry, and now feeds image gen for visual continuity across scenes set in the same place. New files: `server/services/writersRoom/settings.js`, `client/src/components/writers-room/SettingsBible.jsx`, `data{,sample}/prompts/stages/writers-room-settings.md`. Touched: `server/lib/{validation,writersRoomPresets}.js`, `server/services/writersRoom/evaluator.js`, `server/routes/writersRoom.js`, `data{,sample}/prompts/{stages/writers-room-script.md,stage-config.json}`, `client/src/{services/apiWritersRoom.js,components/writers-room/{WorkEditor,StoryboardPanel,SceneCard,sceneCardHelpers}.jsx}`.
+
- **Writers Room — Codex / Claude Code CLI support for AI passes, and tail-truncated CLI errors so failures are actually readable.** `callCliProvider` previously branched on `gemini-cli` and treated everything else as "spawn the binary, pipe prompt to stdin" — which Codex and Claude Code reject because they need a subcommand to run non-interactively. Picking Codex as the Adapt LLM exited code 1 with `Error: stdin is not a terminal` because `codex` defaulted to its REPL; Claude Code would have the same gap. Replaced the binary `isGeminiCli` switch with a `buildCliInvocation(provider, model)` dispatcher mirroring `runner.js` / `agentCliSpawning.js`: `codex` → `exec [--model <m>] -`, `claude-code` / `claude-code-bedrock` → `-p - [--model <m>]`, `gemini-cli` → unchanged (`--prompt` arg + `stdio[0] = 'ignore'`), default → spawn binary and pipe prompt to stdin. Also flipped CLI error truncation from `slice(0, 500)` → `slice(-2000)` since the actual failure (e.g. `"The 'gpt-5' model is not supported when using Codex with a ChatGPT account"`) lives at the end of stderr — the head-truncation was clipping the banner and hiding the real cause. Touched: `server/services/writersRoom/evaluator.js`.
- **Writers Room — per-stage provider/model picker in Storyboard settings, and surfaced Adapt failures.** The storyboard's gear-icon settings drawer now exposes an **Adapt LLM** picker with the same Tier-vs-Specific toggle the global Prompt Manager uses (`Tier: default/quick/coding/heavy` or `Specific: <provider> + <model>`). Picking a value PUTs `/api/prompts/writers-room-script` so the same selector works from `/prompts` or any panel that runs the stage. The evaluator's `callAI` now reads `stage.provider` + `stage.model` first (falling back to active provider only when no override is set) and resolves tier names through the provider's `defaultModel`/`lightModel`/`mediumModel`/`heavyModel`, fixing a case where every Writers Room AI pass silently routed through `getActiveProvider()` regardless of stage config. The Storyboard panel also now surfaces failed runs: instead of silently falling back to "No storyboard yet" when the latest Adapt snapshot is `failed`, it shows an error banner with the actual error message, an `Adjust LLM` shortcut into the settings drawer, and a `Re-run Adapt` button. (The 5-minute Gemini-CLI timeout that prompted this — `CLI AI call timed out after 300000ms` on a 4,800-word draft — was the original symptom: the call had been failing on disk for hours but the UI just looked empty.) New file: `client/src/components/writers-room/StagePromptModelPicker.jsx`. Touched: `server/services/writersRoom/evaluator.js`, `client/src/components/writers-room/StoryboardPanel.jsx`.
diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsx
index 29957067e7..03078c61f0 100644
--- a/client/src/components/writers-room/SceneCard.jsx
+++ b/client/src/components/writers-room/SceneCard.jsx
@@ -17,8 +17,9 @@ import socket from '../../services/socket';
import useClickOutside from '../../hooks/useClickOutside';
import {
WR_IMAGE_DEFAULTS,
- buildScenePromptWithCharacters,
+ buildScenePrompt,
matchSceneCharacters,
+ matchSceneSetting,
normCharKey,
} from './sceneCardHelpers';
@@ -32,6 +33,7 @@ const SceneCard = forwardRef(function SceneCard({
initialImage = null,
readingTheme = 'dark',
charByKey = null,
+ settingByKey = null,
isActive = false,
onJumpToProse = null,
onDebug = null,
@@ -41,6 +43,10 @@ const SceneCard = forwardRef(function SceneCard({
() => matchSceneCharacters(scene.characters, charByKey),
[scene.characters, charByKey]
);
+ const matchedSetting = useMemo(
+ () => matchSceneSetting(scene.slugline, settingByKey),
+ [scene.slugline, settingByKey]
+ );
const matchedNameKeys = useMemo(() => {
const keys = new Set();
for (const c of matchedCharacters) {
@@ -143,7 +149,7 @@ const SceneCard = forwardRef(function SceneCard({
setError(null);
setProgress(null);
setGenerated(null);
- const prompt = buildScenePromptWithCharacters(workTitle, scene, matchedCharacters, imageStyle?.prompt || '');
+ const prompt = buildScenePrompt(workTitle, scene, matchedCharacters, imageStyle?.prompt || '', matchedSetting);
const stepsNum = imageCfg.steps ? Number(imageCfg.steps) : undefined;
const seedNum = imageCfg.seed && Number(imageCfg.seed) >= 0 ? Number(imageCfg.seed) : undefined;
const res = await generateImage({
diff --git a/client/src/components/writers-room/SettingsBible.jsx b/client/src/components/writers-room/SettingsBible.jsx
new file mode 100644
index 0000000000..c4b5652cec
--- /dev/null
+++ b/client/src/components/writers-room/SettingsBible.jsx
@@ -0,0 +1,302 @@
+import { useEffect, useState } from 'react';
+import { AlertTriangle, Check, Loader2, MapPin, Pencil, Plus, Trash2, X } from 'lucide-react';
+import toast from '../ui/Toast';
+import {
+ listWritersRoomSettings,
+ createWritersRoomSetting,
+ updateWritersRoomSetting,
+ deleteWritersRoomSetting,
+} from '../../services/apiWritersRoom';
+import useMounted from '../../hooks/useMounted';
+
+const SETTING_FIELDS = [
+ { key: 'description', label: 'Description', placeholder: 'Architecture, scale, materials, lighting sources, recurring set-dressing. Used directly in image-gen prompts.', kind: 'multiline', rows: 3 },
+ { key: 'palette', label: 'Palette', placeholder: 'Comma-separated dominant colors / lighting cues', kind: 'text' },
+ { key: 'era', label: 'Era', placeholder: 'near-future, 1950s noir, present day…', kind: 'text' },
+ { key: 'weather', label: 'Weather / mood', placeholder: 'Recurring atmospheric conditions inside this place', kind: 'text' },
+ { key: 'recurringDetails', label: 'Recurring details', placeholder: 'Distinctive props or fixtures the prose returns to', kind: 'multiline', rows: 2 },
+ { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },
+];
+
+// Editable setting/world bible — persistent across analysis runs and consumed
+// by image gen to inject location descriptions into per-scene prompts.
+//
+// Controlled vs. uncontrolled: caller may pass `settings` to keep multiple
+// mounts in sync (e.g. drawer + storyboard chip count). When omitted we fetch
+// and own the list so this can stand alone.
+export default function SettingsBible({ workId, settings: settingsProp, onSettingsChange, readingTheme = 'dark' }) {
+ const [internalSettings, setInternalSettings] = useState(settingsProp || []);
+ const settings = settingsProp ?? internalSettings;
+ const [editingId, setEditingId] = useState(null);
+ const [creating, setCreating] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const mountedRef = useMounted();
+
+ useEffect(() => {
+ if (settingsProp) return;
+ if (!workId) return;
+ setLoading(true);
+ listWritersRoomSettings(workId)
+ .then((list) => { if (mountedRef.current) setInternalSettings(list); })
+ .catch(() => { if (mountedRef.current) setInternalSettings([]); })
+ .finally(() => { if (mountedRef.current) setLoading(false); });
+ }, [workId, settingsProp, mountedRef]);
+
+ const upsert = (next) => {
+ const update = (prev) => {
+ const idx = prev.findIndex((s) => s.id === next.id);
+ const sorted = (arr) => arr.sort((a, b) => (a.slugline || a.name || '').localeCompare(b.slugline || b.name || ''));
+ if (idx < 0) return sorted([...prev, next]);
+ const copy = [...prev];
+ copy[idx] = next;
+ return sorted(copy);
+ };
+ setInternalSettings(update);
+ onSettingsChange?.(update(settings));
+ };
+
+ const removeOne = (id) => {
+ const next = settings.filter((s) => s.id !== id);
+ setInternalSettings(next);
+ onSettingsChange?.(next);
+ };
+
+ return (
+ <div className="text-xs">
+ <div className="flex items-center justify-between mb-2">
+ <div className="text-[11px] text-gray-500">
+ {settings.length} location{settings.length === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.
+ </div>
+ <button
+ onClick={() => { setCreating(true); setEditingId(null); }}
+ className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-port-accent"
+ >
+ <Plus size={12} /> Add
+ </button>
+ </div>
+
+ {loading && settings.length === 0 && (
+ <div className="text-gray-500 italic">Loading…</div>
+ )}
+
+ {!loading && settings.length === 0 && !creating && (
+ <div className="text-gray-500 italic px-1 mb-2">
+ No locations yet. Run "Refresh Settings" from the work menu, or add one manually.
+ </div>
+ )}
+
+ {creating && (
+ <SettingEditor
+ workId={workId}
+ setting={null}
+ onSaved={(s) => { upsert(s); setCreating(false); }}
+ onCancel={() => setCreating(false)}
+ />
+ )}
+
+ <ul className="space-y-1.5">
+ {settings.map((s) => {
+ const isEditing = editingId === s.id;
+ if (isEditing) {
+ return (
+ <li key={s.id}>
+ <SettingEditor
+ workId={workId}
+ setting={s}
+ onSaved={(updated) => { upsert(updated); setEditingId(null); }}
+ onDeleted={() => { removeOne(s.id); setEditingId(null); }}
+ onCancel={() => setEditingId(null)}
+ />
+ </li>
+ );
+ }
+ return (
+ <li key={s.id} className="border border-port-border rounded">
+ <SettingRow setting={s} onEdit={() => setEditingId(s.id)} readingTheme={readingTheme} />
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
+
+function SettingRow({ setting, onEdit, readingTheme }) {
+ const light = readingTheme === 'light';
+ const blanks = SETTING_FIELDS.filter((f) => {
+ if (f.key === 'notes') return false;
+ return !String(setting[f.key] || '').trim();
+ });
+ return (
+ <div className="px-3 py-2">
+ <div className="flex items-start gap-2">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <MapPin size={11} className="text-port-accent shrink-0" />
+ {setting.slugline ? (
+ <span className={`font-mono text-[11px] uppercase ${light ? 'text-gray-900' : 'text-white'}`}>{setting.slugline}</span>
+ ) : (
+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{setting.name}</span>
+ )}
+ {setting.slugline && setting.name && setting.name !== setting.slugline && (
+ <span className="text-[10px] text-gray-500 truncate">aka {setting.name}</span>
+ )}
+ {setting.era && (
+ <span className="text-[9px] uppercase tracking-wider text-port-accent">{setting.era}</span>
+ )}
+ {setting.source === 'ai' && (
+ <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>
+ )}
+ </div>
+ {setting.description ? (
+ <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>
+ {setting.description}
+ </div>
+ ) : (
+ <div className="text-[11px] mt-0.5 text-port-warning italic">No description — image gen will use the scene's visualPrompt only</div>
+ )}
+ {setting.palette && (
+ <div className="text-[10px] text-gray-500 mt-1">
+ <span className="uppercase tracking-wider text-[9px]">Palette:</span> {setting.palette}
+ </div>
+ )}
+ {setting.recurringDetails && (
+ <div className="text-[10px] text-gray-500 mt-0.5">
+ <span className="uppercase tracking-wider text-[9px]">Anchors:</span> {setting.recurringDetails}
+ </div>
+ )}
+ {blanks.length > 0 && (
+ <div className="text-[10px] text-port-warning mt-1 flex items-center gap-1">
+ <AlertTriangle size={9} /> Missing: {blanks.map((f) => f.label.toLowerCase()).join(', ')}
+ </div>
+ )}
+ {setting.missingFromProse?.length > 0 && (
+ <div className="text-[10px] text-gray-500 mt-1">
+ <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {setting.missingFromProse.join(', ')}
+ </div>
+ )}
+ </div>
+ <button
+ onClick={onEdit}
+ className="text-gray-500 hover:text-port-accent shrink-0"
+ title="Edit setting"
+ aria-label={`Edit ${setting.slugline || setting.name}`}
+ >
+ <Pencil size={11} />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function SettingEditor({ workId, setting, onSaved, onDeleted, onCancel }) {
+ const isCreate = !setting;
+ const [draft, setDraft] = useState(() => {
+ const seed = {
+ slugline: setting?.slugline || '',
+ name: setting?.name || '',
+ };
+ for (const f of SETTING_FIELDS) {
+ seed[f.key] = setting?.[f.key] || '';
+ }
+ return seed;
+ });
+ const [saving, setSaving] = useState(false);
+
+ const set = (field) => (e) => setDraft((d) => ({ ...d, [field]: e.target.value }));
+
+ const save = async () => {
+ if (!draft.slugline.trim() && !draft.name.trim()) {
+ toast.error('Slugline or name is required');
+ return;
+ }
+ setSaving(true);
+ const payload = {
+ slugline: draft.slugline.trim(),
+ name: draft.name.trim(),
+ };
+ for (const f of SETTING_FIELDS) {
+ payload[f.key] = draft[f.key];
+ }
+ const result = await (isCreate
+ ? createWritersRoomSetting(workId, payload)
+ : updateWritersRoomSetting(workId, setting.id, payload)
+ ).catch((err) => {
+ toast.error(`Save failed: ${err.message}`);
+ return null;
+ });
+ setSaving(false);
+ if (!result) return;
+ toast.success(`${result.slugline || result.name} saved`);
+ onSaved?.(result);
+ };
+
+ const remove = async () => {
+ if (!setting) return;
+ setSaving(true);
+ const ok = await deleteWritersRoomSetting(workId, setting.id).then(() => true).catch((err) => {
+ toast.error(`Delete failed: ${err.message}`);
+ return false;
+ });
+ setSaving(false);
+ if (ok) {
+ toast.success(`${setting.slugline || setting.name} removed`);
+ onDeleted?.();
+ }
+ };
+
+ const inputCls = 'w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200 focus:border-port-accent outline-none';
+
+ return (
+ <div className="border border-port-accent/40 rounded p-2 bg-port-card/40 space-y-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <input
+ value={draft.slugline}
+ onChange={set('slugline')}
+ placeholder="INT. KITCHEN — NIGHT"
+ className={`${inputCls} font-mono uppercase`}
+ />
+ <button
+ onClick={onCancel}
+ className="text-gray-500 hover:text-white shrink-0"
+ aria-label="Cancel edit"
+ title="Cancel"
+ >
+ <X size={12} />
+ </button>
+ </div>
+ <label className="block">
+ <span className="text-[9px] uppercase tracking-wider text-gray-500">Name (optional, human-readable)</span>
+ <input value={draft.name} onChange={set('name')} placeholder="The Kitchen, Curry O'City…" className={inputCls} />
+ </label>
+ {SETTING_FIELDS.map((f) => (
+ <label key={f.key} className="block">
+ <span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>
+ {f.kind === 'multiline' ? (
+ <textarea value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} rows={f.rows || 2} className={`${inputCls} font-sans resize-y`} />
+ ) : (
+ <input value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} className={inputCls} />
+ )}
+ </label>
+ ))}
+ <div className="flex items-center justify-between pt-1">
+ {!isCreate ? (
+ <button
+ onClick={remove}
+ disabled={saving}
+ className="flex items-center gap-1 text-[10px] text-port-error hover:underline disabled:opacity-50"
+ >
+ <Trash2 size={10} /> Delete
+ </button>
+ ) : <span />}
+ <button
+ onClick={save}
+ disabled={saving}
+ className="flex items-center gap-1 px-2 py-1 bg-port-accent text-white rounded text-[10px] hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ {saving ? <Loader2 size={10} className="animate-spin" /> : <Check size={10} />} Save
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsx
index c2e6e7c258..4055eec554 100644
--- a/client/src/components/writers-room/StoryboardPanel.jsx
+++ b/client/src/components/writers-room/StoryboardPanel.jsx
@@ -16,6 +16,7 @@ import StagePromptModelPicker from './StagePromptModelPicker';
import {
WR_IMAGE_DEFAULTS,
buildCharByKey,
+ buildSettingByKey,
readWrImageSettings,
STYLE_ID,
EMPTY_IMAGE_STYLE,
@@ -26,6 +27,7 @@ const SCRIPT_STAGE = 'writers-room-script';
export default function StoryboardPanel({
work,
characters = [],
+ settings = [],
onJumpToScene,
onDebug,
onRunAdapt,
@@ -140,6 +142,7 @@ export default function StoryboardPanel({
}, []);
const charByKey = useMemo(() => buildCharByKey(characters), [characters]);
+ const settingByKey = useMemo(() => buildSettingByKey(settings), [settings]);
const activeDraft = (work.drafts || []).find((d) => d.id === work.activeDraftVersionId);
const activeHash = activeDraft?.contentHash || null;
const isStale = !!latestScript?.sourceContentHash && !!activeHash && latestScript.sourceContentHash !== activeHash;
@@ -241,6 +244,7 @@ export default function StoryboardPanel({
initialImage={sceneImages[sceneId] || null}
readingTheme={readingTheme}
charByKey={charByKey}
+ settingByKey={settingByKey}
isActive={sceneId === activeSceneId}
onJumpToProse={onJumpToScene ? () => onJumpToScene(scene, i, scenes.length) : null}
onDebug={onDebug}
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index 83488e3b04..b94c8df75e 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -9,6 +9,7 @@ import {
Sparkles,
FileSignature,
Users,
+ MapPin,
ListTree,
Clock,
History,
@@ -28,20 +29,23 @@ import {
updateWritersRoomWork,
runWritersRoomAnalysis,
listWritersRoomCharacters,
+ listWritersRoomSettings,
} from '../../services/apiWritersRoom';
import { STATUS_LABELS } from './labels';
import { countWords } from '../../utils/formatters';
import StoryboardPanel from './StoryboardPanel';
import CharactersBible from './CharactersBible';
+import SettingsBible from './SettingsBible';
import AnalysisHistory from './AnalysisHistory';
-const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', EVALUATE: 'evaluate', FORMAT: 'format' };
-const DRAWER = { OUTLINE: 'outline', VERSIONS: 'versions', CHARACTERS: 'characters', HISTORY: 'history' };
+const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', SETTINGS: 'settings', EVALUATE: 'evaluate', FORMAT: 'format' };
+const DRAWER = { OUTLINE: 'outline', VERSIONS: 'versions', CHARACTERS: 'characters', SETTINGS: 'settings', HISTORY: 'history' };
const MOBILE_TAB = { WRITING: 'writing', STORYBOARD: 'storyboard' };
const ANALYSIS_LABELS = {
[ANALYSIS_KIND.SCRIPT]: 'Adapt',
[ANALYSIS_KIND.CHARACTERS]: 'Characters',
+ [ANALYSIS_KIND.SETTINGS]: 'Settings',
[ANALYSIS_KIND.EVALUATE]: 'Editorial pass',
[ANALYSIS_KIND.FORMAT]: 'Format pass',
};
@@ -78,6 +82,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const [saving, setSaving] = useState(false);
const [readingTheme, setReadingTheme] = useState(readReadingTheme);
const [characters, setCharacters] = useState([]);
+ const [settings, setSettings] = useState([]);
const [runningKind, setRunningKind] = useState(null);
const [drawer, setDrawer] = useState(null);
const [overflowOpen, setOverflowOpen] = useState(false);
@@ -102,12 +107,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
useEffect(() => { setStatus(work.status); }, [work.status]);
useEffect(() => { setTitle(work.title); }, [work.title]);
- // The CharactersBible drawer is the canonical editor; mirror its list here
- // so the storyboard's image-prompt enrichment picks up edits immediately.
+ // The CharactersBible / SettingsBible drawers are the canonical editors;
+ // mirror their lists here so the storyboard's image-prompt enrichment picks
+ // up edits immediately.
useEffect(() => {
listWritersRoomCharacters(work.id)
.then((list) => setCharacters(list || []))
.catch(() => setCharacters([]));
+ listWritersRoomSettings(work.id)
+ .then((list) => setSettings(list || []))
+ .catch(() => setSettings([]));
}, [work.id]);
const dirty = body !== savedBody;
@@ -239,6 +248,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
if (kind === 'characters' && Array.isArray(snapshot.result?.mergedProfiles)) {
setCharacters(snapshot.result.mergedProfiles);
}
+ if (kind === 'settings' && Array.isArray(snapshot.result?.mergedProfiles)) {
+ setSettings(snapshot.result.mergedProfiles);
+ }
if (kind === 'format' && snapshot.result?.formattedBody) {
setBody(snapshot.result.formattedBody);
toast('Format applied to draft buffer — save to persist', { icon: '💾' });
@@ -411,6 +423,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<MenuSection label="AI">
<MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === ANALYSIS_KIND.SCRIPT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SCRIPT))} />
<MenuItem icon={Users} label="Refresh characters" running={runningKind === ANALYSIS_KIND.CHARACTERS} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.CHARACTERS))} />
+ <MenuItem icon={MapPin} label="Refresh settings" running={runningKind === ANALYSIS_KIND.SETTINGS} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SETTINGS))} />
<MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} />
<MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} />
</MenuSection>
@@ -418,6 +431,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<MenuItem icon={ListTree} label="Outline" onClick={closeOverflowAnd(() => setDrawer(DRAWER.OUTLINE))} />
<MenuItem icon={Clock} label="Versions" onClick={closeOverflowAnd(() => setDrawer(DRAWER.VERSIONS))} />
<MenuItem icon={Users} label="Characters" badge={characters.length || null} onClick={closeOverflowAnd(() => setDrawer(DRAWER.CHARACTERS))} />
+ <MenuItem icon={MapPin} label="Settings" badge={settings.length || null} onClick={closeOverflowAnd(() => setDrawer(DRAWER.SETTINGS))} />
<MenuItem icon={History} label="Analysis history" onClick={closeOverflowAnd(() => setDrawer(DRAWER.HISTORY))} />
</MenuSection>
<MenuSection label="View">
@@ -491,6 +505,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<StoryboardPanel
work={work}
characters={characters}
+ settings={settings}
onJumpToScene={jumpToScene}
onDebug={handleDebug}
onRunAdapt={() => runAnalysis(ANALYSIS_KIND.SCRIPT)}
@@ -516,6 +531,14 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
readingTheme={readingTheme}
/>
</Drawer>
+ <Drawer open={drawer === DRAWER.SETTINGS} onClose={() => setDrawer(null)} title="Settings (locations / world bible)">
+ <SettingsBible
+ workId={work.id}
+ settings={settings}
+ onSettingsChange={setSettings}
+ readingTheme={readingTheme}
+ />
+ </Drawer>
<Drawer open={drawer === DRAWER.HISTORY} onClose={() => setDrawer(null)} title="Analysis history">
<AnalysisHistory work={work} activeHash={activeHash} onApplyFormat={applyFormatText} />
</Drawer>
diff --git a/client/src/components/writers-room/sceneCardHelpers.js b/client/src/components/writers-room/sceneCardHelpers.js
index 65c93d8572..955f18a503 100644
--- a/client/src/components/writers-room/sceneCardHelpers.js
+++ b/client/src/components/writers-room/sceneCardHelpers.js
@@ -63,34 +63,95 @@ export function matchSceneCharacters(sceneCharacterNames = [], charByKey) {
return matched;
}
+// Match server's normalizeSlugline in services/writersRoom/settings.js — the
+// pair has to agree byte-for-byte or the bible's match keys won't line up
+// with the live scene matching here.
+export const normSlugline = (s) => String(s || '')
+ .toUpperCase()
+ .replace(/[—–-]/g, ' ')
+ .replace(/[.,:;]/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+
+export function buildSettingByKey(allSettings) {
+ const map = new Map();
+ for (const setting of allSettings || []) {
+ const key = normSlugline(setting.slugline || setting.name);
+ if (!key) continue;
+ map.set(key, setting);
+ }
+ return map;
+}
+
+export function matchSceneSetting(sceneSlugline, settingByKey) {
+ if (!sceneSlugline) return null;
+ return settingByKey?.get(normSlugline(sceneSlugline)) || null;
+}
+
const PROMPT_MAX = 1900;
-// scene.visualPrompt is the load-bearing part of the image prompt — it must
-// always survive truncation. Reserve room for style + title + visual prompt
-// first, then fit the "Featuring" block into whatever is left, dropping
-// characters one-by-one if needed. The world style goes FIRST because
-// diffusion models weight early tokens heaviest.
-export function buildScenePromptWithCharacters(workTitle, scene, matchedCharacters, worldStyle = '') {
+// Build the final image-gen prompt with priority order (diffusion models
+// weight earlier tokens heaviest):
+// 1. worldStyle preset (cinematic / film-noir / etc.) — broadest aesthetic
+// 2. workTitle — gives the model story-context cues
+// 3. setting baseline (description / palette / recurring details) — the place
+// 4. Featuring — char1: desc, char2: desc — the subjects
+// 5. scene.visualPrompt — what's NEW this beat
+//
+// Truncation priority is the inverse: visualPrompt survives unconditionally,
+// then setting baseline, then characters. Style + title are short so they're
+// always kept. Featuring drops characters one-by-one to fit; setting drops
+// secondary fields (palette, recurring) before description.
+export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle = '', matchedSetting = null) {
const stylePart = worldStyle && worldStyle.trim() ? `${worldStyle.trim()}. ` : '';
const titlePart = workTitle ? `${workTitle}. ` : '';
const visual = scene.visualPrompt || '';
+
+ const settingFrags = matchedSetting ? [
+ matchedSetting.description?.trim() || '',
+ matchedSetting.palette ? `Palette: ${matchedSetting.palette.trim()}.` : '',
+ matchedSetting.recurringDetails?.trim() || '',
+ ].filter(Boolean) : [];
+
const featuringFragments = (matchedCharacters || [])
.filter((c) => c.physicalDescription && c.physicalDescription.trim())
.map((c) => `${c.name}: ${c.physicalDescription.trim()}`);
+
const PREFIX = 'Featuring — ';
- const reserveForVisual = stylePart.length + titlePart.length + visual.length + 1;
- let budget = PROMPT_MAX - reserveForVisual - PREFIX.length;
- const fitFragments = [];
+ const reserveCore = stylePart.length + titlePart.length + visual.length + 4;
+ let budget = PROMPT_MAX - reserveCore;
+
+ // Setting first claim on remaining budget (place baseline > characters
+ // for visual continuity across scenes).
+ const settingFit = [];
+ for (const frag of settingFrags) {
+ const cost = (settingFit.length === 0 ? 0 : 1) + frag.length;
+ if (cost > budget) break;
+ settingFit.push(frag);
+ budget -= cost;
+ }
+
+ // Then characters fill what's left, prefix included.
+ budget -= PREFIX.length;
+ const charFit = [];
for (const frag of featuringFragments) {
- const cost = (fitFragments.length === 0 ? 0 : 1) + frag.length;
+ const cost = (charFit.length === 0 ? 0 : 1) + frag.length;
if (cost > budget) break;
- fitFragments.push(frag);
+ charFit.push(frag);
budget -= cost;
}
+
const segs = [];
if (stylePart) segs.push(stylePart.trim());
if (titlePart) segs.push(titlePart.trim());
- if (fitFragments.length > 0) segs.push(`${PREFIX}${fitFragments.join(' ')}`);
+ if (settingFit.length > 0) segs.push(settingFit.join(' '));
+ if (charFit.length > 0) segs.push(`${PREFIX}${charFit.join(' ')}`);
if (visual) segs.push(visual);
return segs.filter(Boolean).join(' ').slice(0, PROMPT_MAX);
}
+
+// Backward-compatible alias — older callers (and tests) used the previous
+// name. New code should use `buildScenePrompt` so the setting param is
+// discoverable.
+export const buildScenePromptWithCharacters = (workTitle, scene, matchedCharacters, worldStyle = '') =>
+ buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle, null);
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index 3310e61d4c..06d237dc0a 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -77,6 +77,25 @@ export const deleteWritersRoomCharacter = (workId, characterId) =>
method: 'DELETE',
});
+// Settings / world bible (editable, persists across analysis runs, drives
+// scene image gen via slugline match in SceneCard)
+export const listWritersRoomSettings = (workId) =>
+ request(`/writers-room/works/${enc(workId)}/settings`);
+export const createWritersRoomSetting = (workId, data) =>
+ request(`/writers-room/works/${enc(workId)}/settings`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ });
+export const updateWritersRoomSetting = (workId, settingId, patch) =>
+ request(`/writers-room/works/${enc(workId)}/settings/${enc(settingId)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ });
+export const deleteWritersRoomSetting = (workId, settingId) =>
+ request(`/writers-room/works/${enc(workId)}/settings/${enc(settingId)}`, {
+ method: 'DELETE',
+ });
+
// Exercises
export const listWritersRoomExercises = (workId) => {
const qs = workId ? `?workId=${enc(workId)}` : '';
diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.json
index fa2d6b497a..9778fab86a 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -28,6 +28,13 @@
"returnsJson": true,
"variables": []
},
+ "writers-room-settings": {
+ "name": "Writers Room — Setting / World Bible",
+ "description": "Extract a setting/world bible from a Writers Room draft: per-location descriptions keyed by screenplay slugline (palette, era, weather, recurring details). Storyboard scenes match their slugline back to a setting and inject its description into the image prompt for visual continuity.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"cd-treatment": {
"name": "Creative Director — Treatment",
"description": "Plan a long-form generated-video project: write the logline, synopsis, and scene-by-scene treatment.",
diff --git a/data.sample/prompts/stages/writers-room-script.md b/data.sample/prompts/stages/writers-room-script.md
index e467b7ced7..74420d8d79 100644
--- a/data.sample/prompts/stages/writers-room-script.md
+++ b/data.sample/prompts/stages/writers-room-script.md
@@ -8,6 +8,25 @@ You are a script supervisor breaking a piece of prose into the smallest visualiz
- Kind: {{work.kind}}
- Word count: {{work.wordCount}}
+## Character bible (canonical descriptions — defer to these)
+
+Each scene's image-gen prompt has to describe characters physically (image models don't know your story). When the prose names a character that has an entry below, write `visualPrompt` to match the bible's `physicalDescription` rather than re-improvising. If the bible is empty, fall back to the prose. Do **not** invent contradictory details.
+
+```json
+{{existingCharactersJson}}
+```
+
+## Setting bible (canonical locations — defer to these)
+
+When a scene's slugline matches a `slugline` below (case-insensitive, ignoring punctuation), the storyboard pipeline auto-injects the entry's `description` / `palette` / `recurringDetails` into the final image prompt. So:
+
+- **Reuse the same slugline string** from the bible verbatim when the scene takes place in that location — even minor wording drift breaks the match.
+- Don't restate the setting's baseline description inside `visualPrompt`; the pipeline will prepend it. Use `visualPrompt` for what's *new this beat* (blocking, lighting *changes* from the room's baseline, character action, time-of-day shifts).
+
+```json
+{{existingSettingsJson}}
+```
+
## Source prose
```
diff --git a/data.sample/prompts/stages/writers-room-settings.md b/data.sample/prompts/stages/writers-room-settings.md
new file mode 100644
index 0000000000..2598ccc9b0
--- /dev/null
+++ b/data.sample/prompts/stages/writers-room-settings.md
@@ -0,0 +1,71 @@
+# Writers Room — Setting / World Bible Extraction
+
+You are a production designer building a setting bible for a piece of prose. Each entry you produce will drive image-generation prompts for scenes set in that location, so descriptions must be specific, visually dense, and renderable — not literary.
+
+## Work being analyzed
+
+- Title: {{work.title}}
+- Kind: {{work.kind}}
+- Word count: {{work.wordCount}}
+
+## Existing settings (preserve user edits — DO NOT contradict these)
+
+The writer may have already edited some entries. Treat any non-empty field below as authoritative — if you would describe the same location differently, defer to the existing value. Your job is to FILL IN the empty fields from prose evidence and ADD any locations the writer hasn't captured yet.
+
+```json
+{{existingSettingsJson}}
+```
+
+## Source prose
+
+```
+{{draftBody}}
+```
+
+## Task
+
+For every distinct *location* the prose stages a scene in (interior or exterior), produce one entry. Use screenplay-slugline keys so the storyboard pipeline can match scenes back to settings automatically.
+
+1. Extract or refine these fields:
+ - `slugline` — screenplay format: `INT./EXT. LOCATION — TIME OF DAY` (uppercase). This is the *match key* the storyboard uses to attach a setting to a scene, so use the same wording every time the prose returns to a place. If the same room appears at different times of day, prefer the most-used variant (or `INT. LOCATION — DAY` as the default). Do not invent locations the prose never visits.
+ - `name` — short human-readable name (`Curry O'City`, `The Train Platform`, `Marlowe's Apartment`). May overlap with the slugline's location half. If the prose names the place, use that name verbatim.
+ - `description` — 40–100 words, image-gen-ready. Be specific and visual: architecture, scale, materials, lighting sources, recurring set-dressing, signage, smells/sounds the prose names visually (steam, neon hum). Bake in genre/era cues. Do NOT include character action, dialogue, or plot — just the *place*.
+ - `palette` — short comma-separated list of dominant colors / lighting cues (`oxblood neon, wet asphalt black, sodium-yellow streetlights`). Drives image-gen color consistency.
+ - `era` — short tag (`near-future`, `1950s noir`, `present day`, `Victorian`). One phrase. Skip if the prose is ambiguous.
+ - `weather` — recurring atmospheric conditions inside this place (`muggy curry-steam`, `dust motes in shafts of sun`, `permanent drizzle out the window`). Skip if the prose doesn't establish one.
+ - `recurringDetails` — 1–2 sentences listing distinctive props or fixtures the prose returns to (`three tiny tables and standing room only`, `a dead jukebox in the corner`). These are the visual anchors that keep scenes in the same place looking the same.
+ - `firstAppearance` — short quote (≤ 120 chars) from the prose where the location first shows up, or null if not clear.
+ - `evidence` — array of 1–3 short verbatim quotes (≤ 120 chars each) from the prose that support the description specifically.
+
+2. **Respect existing edits.** If a field in the existing entry is already filled in, keep that value verbatim. Only populate empty / missing fields.
+
+3. **Identify gaps.** For every entry (existing AND new), list which fields the prose does not yet support — return them as `missingFromProse`. The writer uses this to decide whether to add detail to the prose or fill the field manually.
+
+4. Do not invent details the prose does not support. If the prose never describes the lighting, leave it out of `description` rather than guessing — and call it out in `missingFromProse`.
+
+5. Skip *referenced-only* locations the prose never actually stages a scene in (e.g. "the city she grew up in"). Only entries where the prose puts characters in the place.
+
+6. If the same physical place appears under two sluglines because of time-of-day variants (`INT. KITCHEN — DAY` and `INT. KITCHEN — NIGHT`), produce ONE entry under the most common slugline; cover the time-of-day variation inside `weather` or `description`.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "settings": [
+ {
+ "slugline": "INT. KITCHEN — NIGHT",
+ "name": "string",
+ "description": "string",
+ "palette": "string",
+ "era": "string",
+ "weather": "string",
+ "recurringDetails": "string",
+ "firstAppearance": "string or null",
+ "evidence": ["string", ...],
+ "missingFromProse": ["palette", "weather", ...]
+ }
+ ]
+}
+```
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 983b3830ea..8e27599061 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -559,6 +559,30 @@ export const writersRoomCharacterUpdateSchema = z.object({
notes: wrCharTextField.optional(),
}).strict();
+const wrSettingTextField = z.string().max(2000);
+export const writersRoomSettingCreateSchema = z.object({
+ name: z.string().trim().max(200).optional(),
+ slugline: z.string().trim().max(200).optional(),
+ description: wrSettingTextField.optional(),
+ palette: wrSettingTextField.optional(),
+ era: wrSettingTextField.optional(),
+ weather: wrSettingTextField.optional(),
+ recurringDetails: wrSettingTextField.optional(),
+ notes: wrSettingTextField.optional(),
+}).strict().refine((v) => (v.name && v.name.trim()) || (v.slugline && v.slugline.trim()), {
+ message: 'Setting requires either a slugline or a name',
+});
+export const writersRoomSettingUpdateSchema = z.object({
+ name: z.string().trim().max(200).optional(),
+ slugline: z.string().trim().max(200).optional(),
+ description: wrSettingTextField.optional(),
+ palette: wrSettingTextField.optional(),
+ era: wrSettingTextField.optional(),
+ weather: wrSettingTextField.optional(),
+ recurringDetails: wrSettingTextField.optional(),
+ notes: wrSettingTextField.optional(),
+}).strict();
+
// =============================================================================
// FEATURE AGENT SCHEMAS
// =============================================================================
diff --git a/server/lib/writersRoomPresets.js b/server/lib/writersRoomPresets.js
index b6f772cc33..bc4c83e029 100644
--- a/server/lib/writersRoomPresets.js
+++ b/server/lib/writersRoomPresets.js
@@ -5,4 +5,4 @@
export const WORK_KINDS = ['novel', 'short-story', 'screenplay', 'essay', 'treatment', 'other'];
export const WORK_STATUSES = ['idea', 'drafting', 'revision', 'adaptation', 'rendering', 'complete', 'archived'];
export const EXERCISE_STATUSES = ['running', 'finished', 'discarded'];
-export const ANALYSIS_KINDS = ['evaluate', 'format', 'script', 'characters'];
+export const ANALYSIS_KINDS = ['evaluate', 'format', 'script', 'characters', 'settings'];
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index 4ed95f1002..c0faaa0791 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -17,6 +17,8 @@ import {
writersRoomAnalysisCreateSchema,
writersRoomCharacterCreateSchema,
writersRoomCharacterUpdateSchema,
+ writersRoomSettingCreateSchema,
+ writersRoomSettingUpdateSchema,
} from '../lib/validation.js';
import {
listFolders, createFolder, deleteFolder,
@@ -31,6 +33,9 @@ import {
import {
listCharacters, createCharacter, updateCharacter, deleteCharacter,
} from '../services/writersRoom/characters.js';
+import {
+ listSettings, createSetting, updateSetting, deleteSetting,
+} from '../services/writersRoom/settings.js';
import { addItem as addCollectionItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
@@ -172,6 +177,26 @@ router.delete('/works/:id/characters/:characterId', asyncHandler(async (req, res
res.json(await deleteCharacter(req.params.id, req.params.characterId));
}));
+// ---------- settings (locations / world bible) ----------
+
+router.get('/works/:id/settings', asyncHandler(async (req, res) => {
+ res.json(await listSettings(req.params.id));
+}));
+
+router.post('/works/:id/settings', asyncHandler(async (req, res) => {
+ const data = validateRequest(writersRoomSettingCreateSchema, req.body || {});
+ res.status(201).json(await createSetting(req.params.id, data));
+}));
+
+router.patch('/works/:id/settings/:settingId', asyncHandler(async (req, res) => {
+ const data = validateRequest(writersRoomSettingUpdateSchema, req.body || {});
+ res.json(await updateSetting(req.params.id, req.params.settingId, data));
+}));
+
+router.delete('/works/:id/settings/:settingId', asyncHandler(async (req, res) => {
+ res.json(await deleteSetting(req.params.id, req.params.settingId));
+}));
+
// Persist a scene→generated-image link on the analysis snapshot, AND mirror
// the image into the work's auto-collection so it appears in MediaGen's
// Collections view. Called by SceneCard when image-gen:completed fires.
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
index 7f7f2b540f..c22cc2c32b 100644
--- a/server/services/writersRoom/evaluator.js
+++ b/server/services/writersRoom/evaluator.js
@@ -15,6 +15,7 @@ import { buildPrompt, getStage } from '../promptService.js';
import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';
import { getWorkWithBody } from './local.js';
import { listCharacters, mergeExtractedCharacters } from './characters.js';
+import { listSettings, mergeExtractedSettings } from './settings.js';
import { nowIso, badRequest, notFound } from './_shared.js';
export { ANALYSIS_KINDS };
@@ -24,6 +25,7 @@ const KIND_META = {
format: { stage: 'writers-room-format', returnsJson: false },
script: { stage: 'writers-room-script', returnsJson: true },
characters: { stage: 'writers-room-characters', returnsJson: true },
+ settings: { stage: 'writers-room-settings', returnsJson: true },
};
// Analysis id == kind. Each work keeps at most one snapshot per kind on disk
@@ -259,6 +261,26 @@ const SHAPERS = {
})),
};
},
+ settings: (raw) => {
+ const parsed = extractJson(raw);
+ const list = Array.isArray(parsed.settings) ? parsed.settings : [];
+ return {
+ settings: list
+ .filter((s) => s && typeof s === 'object' && (typeof s.slugline === 'string' || typeof s.name === 'string'))
+ .map((s) => ({
+ slugline: typeof s.slugline === 'string' ? s.slugline.trim() : '',
+ name: typeof s.name === 'string' ? s.name.trim() : '',
+ description: typeof s.description === 'string' ? s.description : '',
+ palette: typeof s.palette === 'string' ? s.palette : '',
+ era: typeof s.era === 'string' ? s.era : '',
+ weather: typeof s.weather === 'string' ? s.weather : '',
+ recurringDetails: typeof s.recurringDetails === 'string' ? s.recurringDetails : '',
+ firstAppearance: typeof s.firstAppearance === 'string' ? s.firstAppearance : null,
+ evidence: Array.isArray(s.evidence) ? s.evidence.filter((e) => typeof e === 'string') : [],
+ missingFromProse: Array.isArray(s.missingFromProse) ? s.missingFromProse.filter((m) => typeof m === 'string') : [],
+ })),
+ };
+ },
};
// ---------- storage ----------
@@ -464,38 +486,52 @@ export async function runAnalysis(workId, { kind } = {}) {
draftBody: body,
returnsJson,
};
- if (kind === 'characters') {
- // Pass the existing bible so the LLM can preserve user edits and only
- // fill blanks. Stripped down to fields the prompt cares about — no ids,
- // timestamps, or source markers.
+ // Strip down each bible to the fields the prompts care about — no ids,
+ // timestamps, or source markers. Same shape goes to both the bible's own
+ // re-extraction (preserve-user-edits) AND to script (Adapt) so it can
+ // cite canonical names + descriptions in visualPrompt fields.
+ const trimCharacter = (c) => ({
+ name: c.name,
+ aliases: c.aliases,
+ role: c.role,
+ physicalDescription: c.physicalDescription,
+ personality: c.personality,
+ background: c.background,
+ });
+ const trimSetting = (s) => ({
+ name: s.name,
+ slugline: s.slugline,
+ description: s.description,
+ palette: s.palette,
+ era: s.era,
+ weather: s.weather,
+ recurringDetails: s.recurringDetails,
+ });
+ if (kind === 'characters' || kind === 'script') {
const existing = await listCharacters(workId);
- variables.existingCharactersJson = JSON.stringify(
- existing.map((c) => ({
- name: c.name,
- aliases: c.aliases,
- role: c.role,
- physicalDescription: c.physicalDescription,
- personality: c.personality,
- background: c.background,
- })),
- null,
- 2
- );
+ variables.existingCharactersJson = JSON.stringify(existing.map(trimCharacter), null, 2);
}
+ if (kind === 'settings' || kind === 'script') {
+ const existing = await listSettings(workId);
+ variables.existingSettingsJson = JSON.stringify(existing.map(trimSetting), null, 2);
+ }
+
const temperature = kind === 'format' ? 0.2 : 0.4;
const { content, model: usedModel, providerId: usedProvider } = await callAI(stage, variables, temperature);
const result = SHAPERS[kind](content);
- let mergedCharacters = null;
+ let mergedProfiles = null;
if (kind === 'characters') {
- mergedCharacters = await mergeExtractedCharacters(workId, result.characters || []);
+ mergedProfiles = await mergeExtractedCharacters(workId, result.characters || []);
+ } else if (kind === 'settings') {
+ mergedProfiles = await mergeExtractedSettings(workId, result.settings || []);
}
const finished = {
...baseSnapshot,
status: 'succeeded',
providerId: usedProvider,
model: usedModel,
- result: mergedCharacters
- ? { ...result, mergedProfiles: mergedCharacters }
+ result: mergedProfiles
+ ? { ...result, mergedProfiles }
: result,
rawResponse: content,
completedAt: nowIso(),
diff --git a/server/services/writersRoom/settings.js b/server/services/writersRoom/settings.js
new file mode 100644
index 0000000000..c9512a6d0c
--- /dev/null
+++ b/server/services/writersRoom/settings.js
@@ -0,0 +1,207 @@
+/**
+ * Writers Room — editable setting/world bible.
+ *
+ * Per-location bible keyed by screenplay slugline (e.g. `INT. KITCHEN — NIGHT`)
+ * so SceneCard can match a scene's slugline to its canonical setting and
+ * inject the description into the image prompt.
+ *
+ * Stored at data/writers-room/works/<workId>/settings.json. Same merge rule
+ * as characters: a re-run of `settings` analysis fills empty fields and adds
+ * new locations, but never overwrites a non-empty field on an existing entry.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../../lib/fileUtils.js';
+import { nowIso, badRequest, notFound } from './_shared.js';
+
+const SETTING_ID_RE = /^wr-setting-[0-9a-f-]+$/i;
+
+const root = () => join(PATHS.data, 'writers-room');
+const settingsFile = (workId) => join(root(), 'works', workId, 'settings.json');
+
+const EDITABLE_FIELDS = ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'recurringDetails', 'notes'];
+
+function emptySetting() {
+ return {
+ id: '',
+ name: '',
+ slugline: '',
+ description: '',
+ palette: '',
+ era: '',
+ weather: '',
+ recurringDetails: '',
+ notes: '',
+ firstAppearance: null,
+ evidence: [],
+ missingFromProse: [],
+ source: 'user',
+ createdAt: nowIso(),
+ updatedAt: nowIso(),
+ };
+}
+
+// Sluglines are matched case-insensitively with whitespace+punctuation
+// collapsed so `INT. KITCHEN — NIGHT` and `INT KITCHEN - NIGHT` resolve to
+// the same bible entry. Em-dashes vs hyphens vs spaces in user-edited prose
+// would otherwise fragment a single location across multiple records.
+export function normalizeSlugline(s) {
+ return String(s || '')
+ .toUpperCase()
+ .replace(/[—–-]/g, ' ')
+ .replace(/[.,:;]/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+function isBlank(v) {
+ if (v == null) return true;
+ if (Array.isArray(v)) return v.length === 0;
+ if (typeof v === 'string') return v.trim() === '';
+ return false;
+}
+
+async function loadFile(workId) {
+ const fallback = { settings: [], updatedAt: null };
+ const parsed = await readJSONFile(settingsFile(workId), fallback);
+ return parsed && Array.isArray(parsed.settings) ? parsed : fallback;
+}
+
+async function saveFile(workId, state) {
+ await ensureDir(join(root(), 'works', workId));
+ await atomicWrite(settingsFile(workId), { ...state, updatedAt: nowIso() });
+}
+
+export async function listSettings(workId) {
+ const state = await loadFile(workId);
+ return state.settings.sort((a, b) => (a.slugline || a.name || '').localeCompare(b.slugline || b.name || ''));
+}
+
+export async function getSetting(workId, settingId) {
+ if (!SETTING_ID_RE.test(settingId)) throw badRequest('Invalid setting id');
+ const state = await loadFile(workId);
+ const found = state.settings.find((s) => s.id === settingId);
+ if (!found) throw notFound('Setting');
+ return found;
+}
+
+export async function createSetting(workId, patch = {}) {
+ const slugline = String(patch.slugline || '').trim();
+ const name = String(patch.name || '').trim();
+ if (!slugline && !name) throw badRequest('Setting requires either a slugline or a name');
+ const state = await loadFile(workId);
+ const key = normalizeSlugline(slugline || name);
+ if (state.settings.some((s) => normalizeSlugline(s.slugline || s.name) === key)) {
+ throw badRequest(`A setting matching "${slugline || name}" already exists`);
+ }
+ const profile = {
+ ...emptySetting(),
+ id: `wr-setting-${randomUUID()}`,
+ slugline,
+ name: name || slugline,
+ source: 'user',
+ };
+ for (const field of EDITABLE_FIELDS) {
+ if (field === 'slugline' || field === 'name') continue;
+ if (patch[field] !== undefined) profile[field] = patch[field];
+ }
+ state.settings.push(profile);
+ await saveFile(workId, state);
+ return profile;
+}
+
+export async function updateSetting(workId, settingId, patch = {}) {
+ if (!SETTING_ID_RE.test(settingId)) throw badRequest('Invalid setting id');
+ const state = await loadFile(workId);
+ const idx = state.settings.findIndex((s) => s.id === settingId);
+ if (idx < 0) throw notFound('Setting');
+ const next = { ...state.settings[idx] };
+ for (const field of EDITABLE_FIELDS) {
+ if (patch[field] === undefined) continue;
+ if (field === 'slugline' || field === 'name') {
+ const newVal = String(patch[field] || '').trim();
+ if (field === 'slugline' && !newVal && !next.name) throw badRequest('Setting needs slugline or name');
+ const key = normalizeSlugline(newVal);
+ if (key) {
+ const conflict = state.settings.some((s) => s.id !== settingId && normalizeSlugline(s.slugline || s.name) === key);
+ if (conflict) throw badRequest(`A setting matching "${newVal}" already exists`);
+ }
+ next[field] = newVal;
+ } else {
+ next[field] = patch[field];
+ }
+ }
+ next.source = 'user';
+ next.updatedAt = nowIso();
+ state.settings[idx] = next;
+ await saveFile(workId, state);
+ return next;
+}
+
+export async function deleteSetting(workId, settingId) {
+ if (!SETTING_ID_RE.test(settingId)) throw badRequest('Invalid setting id');
+ const state = await loadFile(workId);
+ const before = state.settings.length;
+ state.settings = state.settings.filter((s) => s.id !== settingId);
+ if (state.settings.length === before) throw notFound('Setting');
+ await saveFile(workId, state);
+ return { ok: true };
+}
+
+/**
+ * Merge an AI-extracted setting set into the editable bible.
+ * - Existing settings (matched by normalized slugline OR name) keep every
+ * non-blank field. Only blank fields get filled from `extracted`.
+ * - New settings are inserted with `source: 'ai'`.
+ * - `firstAppearance`, `evidence`, `missingFromProse` always reflect the
+ * latest analysis.
+ */
+export async function mergeExtractedSettings(workId, extracted) {
+ if (!Array.isArray(extracted)) return listSettings(workId);
+ const state = await loadFile(workId);
+ const byKey = new Map();
+ for (const s of state.settings) {
+ const key = normalizeSlugline(s.slugline || s.name);
+ if (key) byKey.set(key, s);
+ }
+ for (const incoming of extracted) {
+ if (!incoming || (!incoming.slugline && !incoming.name)) continue;
+ const key = normalizeSlugline(incoming.slugline || incoming.name);
+ const existing = byKey.get(key);
+ if (existing) {
+ for (const field of ['description', 'palette', 'era', 'weather', 'recurringDetails']) {
+ if (isBlank(existing[field]) && !isBlank(incoming[field])) {
+ existing[field] = incoming[field];
+ }
+ }
+ if (isBlank(existing.name) && !isBlank(incoming.name)) {
+ existing.name = String(incoming.name).trim();
+ }
+ existing.firstAppearance = incoming.firstAppearance ?? existing.firstAppearance ?? null;
+ existing.evidence = Array.isArray(incoming.evidence) ? incoming.evidence : (existing.evidence || []);
+ existing.missingFromProse = Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [];
+ existing.updatedAt = nowIso();
+ } else {
+ const profile = {
+ ...emptySetting(),
+ id: `wr-setting-${randomUUID()}`,
+ slugline: String(incoming.slugline || '').trim(),
+ name: String(incoming.name || incoming.slugline || '').trim(),
+ description: String(incoming.description || '').trim(),
+ palette: String(incoming.palette || '').trim(),
+ era: String(incoming.era || '').trim(),
+ weather: String(incoming.weather || '').trim(),
+ recurringDetails: String(incoming.recurringDetails || '').trim(),
+ firstAppearance: incoming.firstAppearance ?? null,
+ evidence: Array.isArray(incoming.evidence) ? incoming.evidence : [],
+ missingFromProse: Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [],
+ source: 'ai',
+ };
+ state.settings.push(profile);
+ byKey.set(normalizeSlugline(profile.slugline || profile.name), profile);
+ }
+ }
+ await saveFile(workId, state);
+ return state.settings.sort((a, b) => (a.slugline || a.name || '').localeCompare(b.slugline || b.name || ''));
+}