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): character bible with image-gen prompt injection

Adam Eivya07d8bc216c6
diff --git a/client/src/components/writers-room/AiPanel.jsx b/client/src/components/writers-room/AiPanel.jsx
index d779831ce0..8aaf5cd668 100644
--- a/client/src/components/writers-room/AiPanel.jsx
+++ b/client/src/components/writers-room/AiPanel.jsx
@@ -1,11 +1,15 @@
-import { useEffect, useState, useCallback, useRef } from 'react';
-import { Sparkles, FileSignature, Clapperboard, Loader2, RotateCcw, AlertTriangle, Image as ImageIcon, Check, Settings as SettingsIcon } from 'lucide-react';
+import { useEffect, useState, useCallback, useRef, useMemo } from 'react';
+import { Sparkles, FileSignature, Clapperboard, Users, Loader2, RotateCcw, AlertTriangle, Image as ImageIcon, Check, Settings as SettingsIcon, Pencil, Trash2, Plus, X } from 'lucide-react';
import toast from '../ui/Toast';
import {
listWritersRoomAnalyses,
runWritersRoomAnalysis,
getWritersRoomAnalysis,
attachWritersRoomSceneImage,
+ listWritersRoomCharacters,
+ createWritersRoomCharacter,
+ updateWritersRoomCharacter,
+ deleteWritersRoomCharacter,
} from '../../services/apiWritersRoom';
import { generateImage, getSettings, updateSettings } from '../../services/apiSystem';
import { listImageModels } from '../../services/apiImageVideo';
@@ -33,9 +37,10 @@ function readWrImageSettings(settings) {
}
const KIND_META = {
- evaluate: { label: 'Evaluate', icon: Sparkles, hint: 'Editorial critique: logline, themes, issues, suggestions' },
- format: { label: 'Format', icon: FileSignature, hint: 'Tidy prose: paragraphing, dialogue, whitespace, typos' },
- script: { label: 'Adapt', icon: Clapperboard, hint: 'Adapt prose into scene-by-scene script with visual prompts' },
+ evaluate: { label: 'Evaluate', icon: Sparkles, hint: 'Editorial critique: logline, themes, issues, suggestions' },
+ format: { label: 'Format', icon: FileSignature, hint: 'Tidy prose: paragraphing, dialogue, whitespace, typos' },
+ script: { label: 'Adapt', icon: Clapperboard, hint: 'Adapt prose into scene-by-scene script with visual prompts' },
+ characters: { label: 'Characters', icon: Users, hint: 'Build/refresh character profiles with image-gen-ready physical descriptions. Preserves your edits — fills gaps from prose.' },
};
const SEVERITY_COLOR = {
@@ -50,6 +55,7 @@ export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' })
const [running, setRunning] = useState(null);
const [expanded, setExpanded] = useState(null);
const [details, setDetails] = useState({});
+ const [characters, setCharacters] = useState([]);
const mountedRef = useRef(true);
useEffect(() => {
@@ -62,13 +68,17 @@ export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' })
const refresh = useCallback(async () => {
setLoadingList(true);
- const list = await listWritersRoomAnalyses(work.id).catch((err) => {
- if (mountedRef.current) toast.error(`Failed to list analyses: ${err.message}`);
- return [];
- });
+ const [list, chars] = await Promise.all([
+ listWritersRoomAnalyses(work.id).catch((err) => {
+ if (mountedRef.current) toast.error(`Failed to list analyses: ${err.message}`);
+ return [];
+ }),
+ listWritersRoomCharacters(work.id).catch(() => []),
+ ]);
if (!mountedRef.current) return;
setLoadingList(false);
setAnalyses(list);
+ setCharacters(chars);
}, [work.id]);
useEffect(() => {
@@ -77,6 +87,7 @@ export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' })
setAnalyses([]);
setExpanded(null);
setDetails({});
+ setCharacters([]);
refresh();
}, [work.id, refresh]);
@@ -100,6 +111,23 @@ export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' })
setDetails((d) => ({ ...d, [snapshot.id]: snapshot }));
setExpanded(snapshot.id);
setAnalyses((prev) => [snapshot, ...prev.filter((a) => a.id !== snapshot.id)]);
+ if (kind === 'characters' && snapshot.status === 'succeeded' && Array.isArray(snapshot.result?.mergedProfiles)) {
+ setCharacters(snapshot.result.mergedProfiles);
+ }
+ };
+
+ const upsertCharacterLocal = (next) => {
+ setCharacters((prev) => {
+ const idx = prev.findIndex((c) => c.id === next.id);
+ if (idx < 0) return [...prev, next].sort((a, b) => (a.name || '').localeCompare(b.name || ''));
+ const copy = [...prev];
+ copy[idx] = next;
+ return copy.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
+ });
+ };
+
+ const removeCharacterLocal = (id) => {
+ setCharacters((prev) => prev.filter((c) => c.id !== id));
};
const expand = async (analysis) => {
@@ -120,7 +148,7 @@ export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' })
<div className="space-y-3 text-xs">
<div>
<h3 className="text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">AI Actions</h3>
- <div className="grid grid-cols-3 gap-1">
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-1">
{Object.entries(KIND_META).map(([kind, meta]) => {
const Icon = meta.icon;
const isRunning = running === kind;
@@ -146,6 +174,14 @@ export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' })
</div>
</div>
+ <CharactersBible
+ workId={work.id}
+ characters={characters}
+ onLocalChange={upsertCharacterLocal}
+ onLocalDelete={removeCharacterLocal}
+ readingTheme={readingTheme}
+ />
+
<div>
<div className="flex items-center justify-between mb-1.5">
<h3 className="text-[10px] uppercase tracking-wider text-gray-500">History</h3>
@@ -208,8 +244,12 @@ export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' })
sceneImages={full.sceneImages || {}}
workTitle={work.title}
readingTheme={readingTheme}
+ characters={characters}
/>
)}
+ {full?.status === 'succeeded' && full.kind === 'characters' && (
+ <CharactersAnalysisResult result={full.result} readingTheme={readingTheme} />
+ )}
</div>
)}
</li>
@@ -302,7 +342,8 @@ function FormatResult({ result, onApply, readingTheme = 'dark' }) {
);
}
-function ScriptResult({ result, workId, analysisId, sceneImages = {}, workTitle, readingTheme = 'dark' }) {
+function ScriptResult({ result, workId, analysisId, sceneImages = {}, workTitle, readingTheme = 'dark', characters = [] }) {
+ const charByKey = useMemo(() => buildCharByKey(characters), [characters]);
// Image-gen settings are scoped to the Writers Room (not the global Image Gen
// page) so a writer can pick a fast/small model + 3:2 aspect without
// disrupting the dedicated Image Gen workflow.
@@ -360,6 +401,7 @@ function ScriptResult({ result, workId, analysisId, sceneImages = {}, workTitle,
imageCfg={imageCfg}
initialImage={sceneImages[sceneId] || null}
readingTheme={readingTheme}
+ charByKey={charByKey}
/>
);
})}
@@ -416,8 +458,78 @@ function ImageGenSettingsRow({ cfg, models, onChange }) {
);
}
-function SceneCard({ scene, workId, analysisId, workTitle, imageCfg = WR_IMAGE_DEFAULTS, initialImage = null, readingTheme = 'dark' }) {
+// LLM scene lists use bare names ("ARIA"), profiles may use full names
+// ("Aria Reyes") or "the bartender" — strip leading "the " and lowercase so
+// either side resolves to the same key.
+const normCharKey = (s) => String(s || '').trim().toLowerCase().replace(/^the\s+/, '');
+
+// Build a name+alias → profile lookup. One pass at the panel level so chip
+// rendering is O(1) per chip instead of O(N) per render.
+function buildCharByKey(allCharacters) {
+ const map = new Map();
+ for (const profile of allCharacters) {
+ map.set(normCharKey(profile.name), profile);
+ for (const alias of profile.aliases || []) map.set(normCharKey(alias), profile);
+ }
+ return map;
+}
+
+function matchSceneCharacters(sceneCharacterNames = [], charByKey) {
+ if (!Array.isArray(sceneCharacterNames) || !sceneCharacterNames.length) return [];
+ const matched = [];
+ const seen = new Set();
+ for (const name of sceneCharacterNames) {
+ const profile = charByKey?.get(normCharKey(name));
+ if (profile && !seen.has(profile.id)) {
+ matched.push(profile);
+ seen.add(profile.id);
+ }
+ }
+ return matched;
+}
+
+const PROMPT_MAX = 1900;
+
+// The scene's visualPrompt is the load-bearing part of the image-gen prompt
+// (location, action, mood) — it must always survive truncation. Reserve room
+// for title + visual prompt first, then fit the "Featuring" block into
+// whatever is left, dropping characters one-by-one if needed.
+function buildScenePromptWithCharacters(workTitle, scene, matchedCharacters) {
+ const titlePart = workTitle ? `${workTitle}. ` : '';
+ const visual = scene.visualPrompt || '';
+ const featuringFragments = matchedCharacters
+ .filter((c) => c.physicalDescription && c.physicalDescription.trim())
+ .map((c) => `${c.name}: ${c.physicalDescription.trim()}`);
+ const PREFIX = 'Featuring — ';
+ const reserveForVisual = titlePart.length + visual.length + 1; // +1 for the join space
+ let budget = PROMPT_MAX - reserveForVisual - PREFIX.length;
+ const fitFragments = [];
+ for (const frag of featuringFragments) {
+ const cost = (fitFragments.length === 0 ? 0 : 1) + frag.length; // +1 for join space
+ if (cost > budget) break;
+ fitFragments.push(frag);
+ budget -= cost;
+ }
+ const segs = [titlePart.trim()];
+ if (fitFragments.length > 0) segs.push(`${PREFIX}${fitFragments.join(' ')}`);
+ if (visual) segs.push(visual);
+ return segs.filter(Boolean).join(' ').slice(0, PROMPT_MAX);
+}
+
+function SceneCard({ scene, workId, analysisId, workTitle, imageCfg = WR_IMAGE_DEFAULTS, initialImage = null, readingTheme = 'dark', charByKey = null }) {
const light = readingTheme === 'light';
+ const matchedCharacters = useMemo(
+ () => matchSceneCharacters(scene.characters, charByKey),
+ [scene.characters, charByKey]
+ );
+ const matchedNameKeys = useMemo(() => {
+ const keys = new Set();
+ for (const c of matchedCharacters) {
+ keys.add(normCharKey(c.name));
+ for (const a of c.aliases || []) keys.add(normCharKey(a));
+ }
+ return keys;
+ }, [matchedCharacters]);
// genStatus drives the button + preview overlay:
// idle → no preview area shown
// running → preview area shows spinner / live diffusion frame from socket
@@ -508,9 +620,7 @@ function SceneCard({ scene, workId, analysisId, workTitle, imageCfg = WR_IMAGE_D
setError(null);
setProgress(null);
setGenerated(null);
- // Truncate at 1900 chars to stay under the 2000-char API limit even when
- // the model returns a chatty visualPrompt.
- const prompt = `${workTitle ? `${workTitle}. ` : ''}${scene.visualPrompt}`.slice(0, 1900);
+ const prompt = buildScenePromptWithCharacters(workTitle, scene, matchedCharacters);
const res = await generateImage({
prompt,
modelId: imageCfg.modelId,
@@ -620,11 +730,21 @@ function SceneCard({ scene, workId, analysisId, workTitle, imageCfg = WR_IMAGE_D
{scene.summary && <div className={light ? 'text-gray-700' : 'text-gray-400'}>{scene.summary}</div>}
{scene.characters?.length > 0 && (
<div className="flex flex-wrap gap-1">
- {scene.characters.map((c, i) => (
- <span key={i} className={`px-1.5 py-0.5 border rounded text-[9px] uppercase tracking-wider ${
- light ? 'bg-white border-gray-300 text-gray-700' : 'bg-port-bg border-port-border'
- }`}>{c}</span>
- ))}
+ {scene.characters.map((c, i) => {
+ const isMatched = matchedNameKeys.has(normCharKey(c));
+ return (
+ <span
+ key={i}
+ title={isMatched ? 'Profile linked — physical description injected into image prompt' : 'No matching profile — run Characters to add'}
+ className={`px-1.5 py-0.5 border rounded text-[9px] uppercase tracking-wider ${
+ isMatched
+ ? 'border-port-accent text-port-accent bg-port-accent/10'
+ : light ? 'bg-white border-gray-300 text-gray-700' : 'bg-port-bg border-port-border'
+ }`}>
+ {c}
+ </span>
+ );
+ })}
</div>
)}
{scene.action && (
@@ -649,3 +769,267 @@ function SceneCard({ scene, workId, analysisId, workTitle, imageCfg = WR_IMAGE_D
</div>
);
}
+
+// ---------- character bible (editable, persistent across analysis runs) ----------
+
+const CHARACTER_FIELDS = [
+ { key: 'aliases', label: 'Aliases', placeholder: 'nicknames, titles (comma-separated)', kind: 'csv' },
+ { key: 'role', label: 'Role', placeholder: 'protagonist, mentor, antagonist…', kind: 'text' },
+ { key: 'physicalDescription', label: 'Physical description', placeholder: 'Age, build, hair, eyes, distinctive features, signature wardrobe. Used directly in image-gen prompts.', kind: 'multiline' },
+ { key: 'personality', label: 'Personality', placeholder: 'Temperament, voice, quirks', kind: 'multiline' },
+ { key: 'background', label: 'Background', placeholder: 'Who they are, where they come from', kind: 'multiline' },
+ { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline' },
+];
+
+function CharactersBible({ workId, characters, onLocalChange, onLocalDelete, readingTheme }) {
+ const [editingId, setEditingId] = useState(null);
+ const [creating, setCreating] = useState(false);
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <h3 className="text-[10px] uppercase tracking-wider text-gray-500">Characters</h3>
+ <button
+ onClick={() => { setCreating(true); setEditingId(null); }}
+ className="flex items-center gap-1 text-[10px] text-gray-500 hover:text-port-accent"
+ title="Add a character profile manually"
+ >
+ <Plus size={11} /> Add
+ </button>
+ </div>
+
+ {characters.length === 0 && !creating && (
+ <div className="text-gray-600 italic px-1 mb-2">
+ No profiles yet. Run <span className="text-gray-400">Characters</span> to extract from prose, or add one manually.
+ </div>
+ )}
+
+ {creating && (
+ <CharacterEditor
+ workId={workId}
+ character={null}
+ onSaved={(c) => { onLocalChange(c); setCreating(false); }}
+ onCancel={() => setCreating(false)}
+ readingTheme={readingTheme}
+ />
+ )}
+
+ <ul className="space-y-1">
+ {characters.map((c) => {
+ const isEditing = editingId === c.id;
+ if (isEditing) {
+ return (
+ <li key={c.id}>
+ <CharacterEditor
+ workId={workId}
+ character={c}
+ onSaved={(updated) => { onLocalChange(updated); setEditingId(null); }}
+ onDeleted={() => { onLocalDelete(c.id); setEditingId(null); }}
+ onCancel={() => setEditingId(null)}
+ readingTheme={readingTheme}
+ />
+ </li>
+ );
+ }
+ return (
+ <li key={c.id} className="border border-port-border rounded">
+ <CharacterRow character={c} onEdit={() => setEditingId(c.id)} readingTheme={readingTheme} />
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
+
+function CharacterRow({ character, onEdit, readingTheme }) {
+ const light = readingTheme === 'light';
+ const blanks = CHARACTER_FIELDS.filter((f) => {
+ if (f.key === 'notes' || f.key === 'aliases') return false;
+ return !String(character[f.key] || '').trim();
+ });
+ return (
+ <div className="px-2 py-1.5">
+ <div className="flex items-start gap-2">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{character.name}</span>
+ {character.role && (
+ <span className="text-[9px] uppercase tracking-wider text-port-accent">{character.role}</span>
+ )}
+ {character.source === 'ai' && (
+ <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>
+ )}
+ {character.aliases?.length > 0 && (
+ <span className="text-[10px] text-gray-500 truncate">aka {character.aliases.join(', ')}</span>
+ )}
+ </div>
+ {character.physicalDescription ? (
+ <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>
+ {character.physicalDescription}
+ </div>
+ ) : (
+ <div className="text-[11px] mt-0.5 text-port-warning italic">No physical description — image gen will use scene context only</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>
+ )}
+ {character.missingFromProse?.length > 0 && (
+ <div className="text-[10px] text-gray-500 mt-1">
+ <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {character.missingFromProse.join(', ')}
+ </div>
+ )}
+ </div>
+ <button
+ onClick={onEdit}
+ className="text-gray-500 hover:text-port-accent shrink-0"
+ title="Edit profile"
+ aria-label={`Edit ${character.name}`}
+ >
+ <Pencil size={11} />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function CharacterEditor({ workId, character, onSaved, onDeleted, onCancel, readingTheme }) {
+ const isCreate = !character;
+ const [draft, setDraft] = useState(() => {
+ const seed = { name: character?.name || '' };
+ for (const f of CHARACTER_FIELDS) {
+ seed[f.key] = f.kind === 'csv' ? (character?.[f.key] || []).join(', ') : (character?.[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.name.trim()) {
+ toast.error('Name is required');
+ return;
+ }
+ setSaving(true);
+ const payload = { name: draft.name.trim() };
+ for (const f of CHARACTER_FIELDS) {
+ payload[f.key] = f.kind === 'csv'
+ ? draft[f.key].split(',').map((s) => s.trim()).filter(Boolean)
+ : draft[f.key];
+ }
+ const result = await (isCreate
+ ? createWritersRoomCharacter(workId, payload)
+ : updateWritersRoomCharacter(workId, character.id, payload)
+ ).catch((err) => {
+ toast.error(`Save failed: ${err.message}`);
+ return null;
+ });
+ setSaving(false);
+ if (!result) return;
+ toast.success(`${result.name} saved`);
+ onSaved?.(result);
+ };
+
+ const remove = async () => {
+ if (!character) return;
+ setSaving(true);
+ const ok = await deleteWritersRoomCharacter(workId, character.id).then(() => true).catch((err) => {
+ toast.error(`Delete failed: ${err.message}`);
+ return false;
+ });
+ setSaving(false);
+ if (ok) {
+ toast.success(`${character.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.name}
+ onChange={set('name')}
+ placeholder="Character name"
+ className={`${inputCls} font-semibold`}
+ />
+ <button
+ onClick={onCancel}
+ className="text-gray-500 hover:text-white shrink-0"
+ aria-label="Cancel edit"
+ title="Cancel"
+ >
+ <X size={12} />
+ </button>
+ </div>
+ {CHARACTER_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.key === 'physicalDescription' ? 3 : 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>
+ );
+}
+
+// Read-only summary of the most recent characters analysis snapshot, shown in
+// the History expander. The editable bible above is the source of truth for
+// scene-image injection — this view exists so the user can compare what came
+// back from this specific run against what's now in the bible.
+function CharactersAnalysisResult({ result, readingTheme }) {
+ const light = readingTheme === 'light';
+ const list = result?.characters || [];
+ if (!list.length) return <div className="text-gray-500">No characters returned.</div>;
+ return (
+ <div className={`space-y-2 text-[11px] ${light ? 'text-gray-900' : 'text-gray-300'}`}>
+ <div className="text-[10px] text-gray-500">
+ {list.length} character{list.length === 1 ? '' : 's'} extracted. Edits to the bible above persist across re-runs.
+ </div>
+ <ul className="space-y-1.5">
+ {list.map((c, i) => (
+ <li key={i} className={`border rounded p-2 ${light ? 'border-gray-300 bg-white' : 'border-port-border bg-port-bg/40'}`}>
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{c.name}</span>
+ {c.role && <span className="text-[9px] uppercase tracking-wider text-port-accent">{c.role}</span>}
+ </div>
+ {c.physicalDescription && (
+ <div className={`mt-1 ${light ? 'text-gray-700' : 'text-gray-400'}`}>{c.physicalDescription}</div>
+ )}
+ {c.missingFromProse?.length > 0 && (
+ <div className="text-[10px] text-port-warning mt-1">
+ Prose gaps: {c.missingFromProse.join(', ')}
+ </div>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index d47ac9d05b..380c1b524d 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -56,6 +56,24 @@ export const attachWritersRoomSceneImage = (workId, analysisId, payload) =>
body: JSON.stringify(payload),
});
+// Characters (editable bible — separate from immutable analysis snapshots)
+export const listWritersRoomCharacters = (workId) =>
+ request(`/writers-room/works/${enc(workId)}/characters`);
+export const createWritersRoomCharacter = (workId, data) =>
+ request(`/writers-room/works/${enc(workId)}/characters`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ });
+export const updateWritersRoomCharacter = (workId, characterId, patch) =>
+ request(`/writers-room/works/${enc(workId)}/characters/${enc(characterId)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ });
+export const deleteWritersRoomCharacter = (workId, characterId) =>
+ request(`/writers-room/works/${enc(workId)}/characters/${enc(characterId)}`, {
+ 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 99bbdff26b..fa2d6b497a 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -21,6 +21,13 @@
"returnsJson": true,
"variables": []
},
+ "writers-room-characters": {
+ "name": "Writers Room — Character Profiles",
+ "description": "Extract a character bible from a Writers Room draft: name, aliases, role, image-gen-ready physical description, personality, and background. Preserves user edits and flags fields the prose does not yet support so the writer knows what to add.",
+ "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-characters.md b/data.sample/prompts/stages/writers-room-characters.md
new file mode 100644
index 0000000000..e66c890147
--- /dev/null
+++ b/data.sample/prompts/stages/writers-room-characters.md
@@ -0,0 +1,67 @@
+# Writers Room — Character Profile Extraction
+
+You are a story analyst building a character bible for a piece of prose. The profiles you produce will drive image-generation prompts for scenes, so physical descriptions must be specific, dense, and renderable — not literary.
+
+## Work being analyzed
+
+- Title: {{work.title}}
+- Kind: {{work.kind}}
+- Word count: {{work.wordCount}}
+
+## Existing profiles (preserve user edits — DO NOT contradict these)
+
+The writer may have already edited some profiles. Treat any non-empty field below as authoritative — if you would describe the same character differently, defer to the existing value. Your job is to FILL IN the empty fields from prose evidence and ADD any characters the writer hasn't captured yet.
+
+```json
+{{existingCharactersJson}}
+```
+
+## Source prose
+
+```
+{{draftBody}}
+```
+
+## Task
+
+For every named character (or distinct unnamed character — "the bartender", "the child") that appears in the prose:
+
+1. Extract or refine these fields:
+ - `name` — canonical name as used most often in the prose. For unnamed characters use a stable role tag like `THE BARTENDER`.
+ - `aliases` — other names / nicknames / titles used for them.
+ - `role` — one phrase: `protagonist`, `antagonist`, `love interest`, `mentor`, `supporting`, `minor`, `narrator`, etc.
+ - `physicalDescription` — 30–80 words, image-gen-ready. Be specific and visual: age range, build, skin tone, hair color/length/style, eye color, distinguishing features, signature wardrobe / silhouette, posture. Bake in genre/era cues so a model with no story context can render them. Do NOT use the character's name inside this field.
+ - `personality` — 1–2 sentences on temperament and voice.
+ - `background` — 1–2 sentences on who they are and where they come from, only what the prose actually establishes.
+ - `firstAppearance` — short quote (≤ 120 chars) from the prose where they first show up, or null if not clear.
+ - `evidence` — array of 1–3 short verbatim quotes (≤ 120 chars each) from the prose that support the physical description specifically.
+
+2. **Respect existing edits.** If a field in the existing profile is already filled in, keep that value verbatim. Only populate empty / missing fields.
+
+3. **Identify gaps.** For every character (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 mentions hair color, leave that out of `physicalDescription` rather than guessing — and call it out in `missingFromProse`.
+
+5. Do not include characters who are merely referenced (e.g. "her dead father") unless they appear in a scene. Use your judgment.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "characters": [
+ {
+ "name": "string",
+ "aliases": ["string", ...],
+ "role": "string",
+ "physicalDescription": "string",
+ "personality": "string",
+ "background": "string",
+ "firstAppearance": "string or null",
+ "evidence": ["string", ...],
+ "missingFromProse": ["physicalDescription.hair", "physicalDescription.eyes", "background", ...]
+ }
+ ]
+}
+```
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 4bf2097d1f..dcf7f42d72 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -523,6 +523,30 @@ export const writersRoomAnalysisCreateSchema = z.object({
kind: z.enum(ANALYSIS_KINDS)
}).strict();
+// Character profile fields are all optional on update so the UI can PATCH
+// one field at a time. `name` accepts trimmed non-empty when present; all
+// other text fields tolerate '' so the writer can deliberately blank a field
+// out and have the next analysis re-fill it.
+const wrCharTextField = z.string().max(2000);
+export const writersRoomCharacterCreateSchema = z.object({
+ name: z.string().trim().min(1).max(200),
+ aliases: z.array(z.string().trim().min(1).max(200)).max(20).optional(),
+ role: wrCharTextField.optional(),
+ physicalDescription: wrCharTextField.optional(),
+ personality: wrCharTextField.optional(),
+ background: wrCharTextField.optional(),
+ notes: wrCharTextField.optional(),
+}).strict();
+export const writersRoomCharacterUpdateSchema = z.object({
+ name: z.string().trim().min(1).max(200).optional(),
+ aliases: z.array(z.string().trim().min(1).max(200)).max(20).optional(),
+ role: wrCharTextField.optional(),
+ physicalDescription: wrCharTextField.optional(),
+ personality: wrCharTextField.optional(),
+ background: wrCharTextField.optional(),
+ notes: wrCharTextField.optional(),
+}).strict();
+
// =============================================================================
// FEATURE AGENT SCHEMAS
// =============================================================================
diff --git a/server/lib/writersRoomPresets.js b/server/lib/writersRoomPresets.js
index 1145b70918..b6f772cc33 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'];
+export const ANALYSIS_KINDS = ['evaluate', 'format', 'script', 'characters'];
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index 7cf8832a93..43feea69df 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -15,6 +15,8 @@ import {
writersRoomExerciseCreateSchema,
writersRoomExerciseFinishSchema,
writersRoomAnalysisCreateSchema,
+ writersRoomCharacterCreateSchema,
+ writersRoomCharacterUpdateSchema,
} from '../lib/validation.js';
import {
listFolders, createFolder, deleteFolder,
@@ -26,6 +28,9 @@ import {
import {
runAnalysis, listAnalyses, getAnalysis, attachSceneImage,
} from '../services/writersRoom/evaluator.js';
+import {
+ listCharacters, createCharacter, updateCharacter, deleteCharacter,
+} from '../services/writersRoom/characters.js';
import { addItem as addCollectionItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
const router = Router();
@@ -142,6 +147,26 @@ router.get('/works/:id/analysis/:analysisId', asyncHandler(async (req, res) => {
res.json(await getAnalysis(req.params.id, req.params.analysisId));
}));
+// ---------- characters ----------
+
+router.get('/works/:id/characters', asyncHandler(async (req, res) => {
+ res.json(await listCharacters(req.params.id));
+}));
+
+router.post('/works/:id/characters', asyncHandler(async (req, res) => {
+ const data = validateRequest(writersRoomCharacterCreateSchema, req.body || {});
+ res.status(201).json(await createCharacter(req.params.id, data));
+}));
+
+router.patch('/works/:id/characters/:characterId', asyncHandler(async (req, res) => {
+ const data = validateRequest(writersRoomCharacterUpdateSchema, req.body || {});
+ res.json(await updateCharacter(req.params.id, req.params.characterId, data));
+}));
+
+router.delete('/works/:id/characters/:characterId', asyncHandler(async (req, res) => {
+ res.json(await deleteCharacter(req.params.id, req.params.characterId));
+}));
+
// 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/_shared.js b/server/services/writersRoom/_shared.js
new file mode 100644
index 0000000000..c2922f304c
--- /dev/null
+++ b/server/services/writersRoom/_shared.js
@@ -0,0 +1,9 @@
+// Tiny helpers shared by every Writers Room service module (local, evaluator,
+// characters). All three need the same iso-stamp + ServerError shorthands;
+// duplicating them turned into byte-for-byte drift risk.
+
+import { ServerError } from '../../lib/errorHandler.js';
+
+export const nowIso = () => new Date().toISOString();
+export const badRequest = (message) => new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });
+export const notFound = (what) => new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' });
diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.js
new file mode 100644
index 0000000000..04153d3371
--- /dev/null
+++ b/server/services/writersRoom/characters.js
@@ -0,0 +1,202 @@
+/**
+ * Writers Room — editable character profile bible.
+ *
+ * Canonical, user-editable character roster per work, stored at
+ * data/writers-room/works/<workId>/characters.json. Distinct from analysis
+ * snapshots: the snapshot in data/.../analysis/ is immutable history; this
+ * file is the working bible that survives across analysis runs and can be
+ * hand-edited by the writer.
+ *
+ * Merge rule: a re-run of `characters` analysis fills empty fields and adds
+ * new characters, but never overwrites a non-empty field on an existing
+ * profile. The writer's edits are authoritative.
+ */
+
+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 CHAR_ID_RE = /^wr-char-[0-9a-f-]+$/i;
+
+const root = () => join(PATHS.data, 'writers-room');
+const charsFile = (workId) => join(root(), 'works', workId, 'characters.json');
+
+const EDITABLE_FIELDS = ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes'];
+
+function emptyProfile() {
+ return {
+ id: '',
+ name: '',
+ aliases: [],
+ role: '',
+ physicalDescription: '',
+ personality: '',
+ background: '',
+ notes: '',
+ firstAppearance: null,
+ evidence: [],
+ missingFromProse: [],
+ source: 'user',
+ createdAt: nowIso(),
+ updatedAt: nowIso(),
+ };
+}
+
+function normalizeName(name) {
+ return String(name || '').trim().toLowerCase();
+}
+
+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 = { characters: [], updatedAt: null };
+ const parsed = await readJSONFile(charsFile(workId), fallback);
+ return parsed && Array.isArray(parsed.characters) ? parsed : fallback;
+}
+
+async function saveFile(workId, state) {
+ await ensureDir(join(root(), 'works', workId));
+ await atomicWrite(charsFile(workId), { ...state, updatedAt: nowIso() });
+}
+
+export async function listCharacters(workId) {
+ const state = await loadFile(workId);
+ return state.characters.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
+}
+
+export async function getCharacter(workId, characterId) {
+ if (!CHAR_ID_RE.test(characterId)) throw badRequest('Invalid character id');
+ const state = await loadFile(workId);
+ const found = state.characters.find((c) => c.id === characterId);
+ if (!found) throw notFound('Character');
+ return found;
+}
+
+export async function createCharacter(workId, patch = {}) {
+ const name = String(patch.name || '').trim();
+ if (!name) throw badRequest('Character name required');
+ const state = await loadFile(workId);
+ if (state.characters.some((c) => normalizeName(c.name) === normalizeName(name))) {
+ throw badRequest(`A character named "${name}" already exists`);
+ }
+ const profile = {
+ ...emptyProfile(),
+ id: `wr-char-${randomUUID()}`,
+ name,
+ source: 'user',
+ };
+ for (const field of EDITABLE_FIELDS) {
+ if (field === 'name') continue;
+ if (patch[field] !== undefined) profile[field] = patch[field];
+ }
+ state.characters.push(profile);
+ await saveFile(workId, state);
+ return profile;
+}
+
+export async function updateCharacter(workId, characterId, patch = {}) {
+ if (!CHAR_ID_RE.test(characterId)) throw badRequest('Invalid character id');
+ const state = await loadFile(workId);
+ const idx = state.characters.findIndex((c) => c.id === characterId);
+ if (idx < 0) throw notFound('Character');
+ const next = { ...state.characters[idx] };
+ for (const field of EDITABLE_FIELDS) {
+ if (patch[field] === undefined) continue;
+ if (field === 'name') {
+ const newName = String(patch.name || '').trim();
+ if (!newName) throw badRequest('Character name cannot be blank');
+ const conflict = state.characters.some((c) => c.id !== characterId && normalizeName(c.name) === normalizeName(newName));
+ if (conflict) throw badRequest(`A character named "${newName}" already exists`);
+ next.name = newName;
+ } else if (field === 'aliases') {
+ next.aliases = Array.isArray(patch.aliases)
+ ? patch.aliases.map((a) => String(a).trim()).filter(Boolean)
+ : [];
+ } else {
+ next[field] = patch[field];
+ }
+ }
+ next.source = 'user';
+ next.updatedAt = nowIso();
+ state.characters[idx] = next;
+ await saveFile(workId, state);
+ return next;
+}
+
+export async function deleteCharacter(workId, characterId) {
+ if (!CHAR_ID_RE.test(characterId)) throw badRequest('Invalid character id');
+ const state = await loadFile(workId);
+ const before = state.characters.length;
+ state.characters = state.characters.filter((c) => c.id !== characterId);
+ if (state.characters.length === before) throw notFound('Character');
+ await saveFile(workId, state);
+ return { ok: true };
+}
+
+/**
+ * Merge an AI-extracted character set into the editable bible.
+ * - Existing characters (matched by case-insensitive name OR by an alias)
+ * keep every non-blank field. Only blank fields get filled from `extracted`.
+ * - New characters are inserted with `source: 'ai'`.
+ * - `firstAppearance`, `evidence`, and `missingFromProse` always reflect the
+ * latest analysis (they're prose-derived, not user-curated).
+ *
+ * Returns the merged character list.
+ */
+export async function mergeExtractedCharacters(workId, extracted) {
+ if (!Array.isArray(extracted)) return listCharacters(workId);
+ const state = await loadFile(workId);
+ const byKey = new Map();
+ for (const c of state.characters) {
+ byKey.set(normalizeName(c.name), c);
+ for (const alias of c.aliases || []) {
+ byKey.set(normalizeName(alias), c);
+ }
+ }
+ for (const incoming of extracted) {
+ if (!incoming || !incoming.name) continue;
+ const key = normalizeName(incoming.name);
+ const existing = byKey.get(key);
+ if (existing) {
+ // Fill in only blank user-editable fields. Prose-derived metadata
+ // (firstAppearance / evidence / missingFromProse) always refreshes.
+ for (const field of ['role', 'physicalDescription', 'personality', 'background']) {
+ if (isBlank(existing[field]) && !isBlank(incoming[field])) {
+ existing[field] = incoming[field];
+ }
+ }
+ if (isBlank(existing.aliases) && Array.isArray(incoming.aliases)) {
+ existing.aliases = incoming.aliases.map((a) => String(a).trim()).filter(Boolean);
+ }
+ 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 = {
+ ...emptyProfile(),
+ id: `wr-char-${randomUUID()}`,
+ name: String(incoming.name).trim(),
+ aliases: Array.isArray(incoming.aliases) ? incoming.aliases.map((a) => String(a).trim()).filter(Boolean) : [],
+ role: String(incoming.role || '').trim(),
+ physicalDescription: String(incoming.physicalDescription || '').trim(),
+ personality: String(incoming.personality || '').trim(),
+ background: String(incoming.background || '').trim(),
+ firstAppearance: incoming.firstAppearance ?? null,
+ evidence: Array.isArray(incoming.evidence) ? incoming.evidence : [],
+ missingFromProse: Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [],
+ source: 'ai',
+ };
+ state.characters.push(profile);
+ byKey.set(normalizeName(profile.name), profile);
+ }
+ }
+ await saveFile(workId, state);
+ return state.characters.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
+}
diff --git a/server/services/writersRoom/characters.test.js b/server/services/writersRoom/characters.test.js
new file mode 100644
index 0000000000..38c30170a4
--- /dev/null
+++ b/server/services/writersRoom/characters.test.js
@@ -0,0 +1,135 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+let tempRoot;
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return new Proxy(actual, {
+ get(target, prop) {
+ if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };
+ return target[prop];
+ },
+ });
+});
+
+const local = await import('./local.js');
+const characters = await import('./characters.js');
+const { createWork } = local;
+const {
+ listCharacters, createCharacter, updateCharacter, deleteCharacter,
+ mergeExtractedCharacters,
+} = characters;
+
+beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-chars-test-'));
+});
+
+afterEach(() => {
+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
+});
+
+async function newWork() {
+ const w = await createWork({ title: 'Test Work', kind: 'short-story' });
+ return w.id;
+}
+
+describe('writers room — characters CRUD', () => {
+ it('starts with an empty bible', async () => {
+ const id = await newWork();
+ expect(await listCharacters(id)).toEqual([]);
+ });
+
+ it('rejects creating without a name', async () => {
+ const id = await newWork();
+ await expect(createCharacter(id, { name: ' ' })).rejects.toThrow(/name required/i);
+ });
+
+ it('rejects duplicate names (case-insensitive)', async () => {
+ const id = await newWork();
+ await createCharacter(id, { name: 'Aria', physicalDescription: 'short' });
+ await expect(createCharacter(id, { name: 'aria' })).rejects.toThrow(/already exists/i);
+ });
+
+ it('creates and updates a profile', async () => {
+ const id = await newWork();
+ const c = await createCharacter(id, { name: 'Mila', physicalDescription: 'tall' });
+ expect(c.name).toBe('Mila');
+ expect(c.physicalDescription).toBe('tall');
+ expect(c.id).toMatch(/^wr-char-/);
+
+ const updated = await updateCharacter(id, c.id, { physicalDescription: 'tall, copper hair' });
+ expect(updated.physicalDescription).toBe('tall, copper hair');
+ expect(updated.source).toBe('user');
+ });
+
+ it('deletes a profile', async () => {
+ const id = await newWork();
+ const c = await createCharacter(id, { name: 'Vox' });
+ await deleteCharacter(id, c.id);
+ expect(await listCharacters(id)).toHaveLength(0);
+ });
+});
+
+describe('writers room — characters merge', () => {
+ it('adds new characters from extraction', async () => {
+ const id = await newWork();
+ const merged = await mergeExtractedCharacters(id, [
+ { name: 'Aria', physicalDescription: 'thirties, athletic, auburn hair', role: 'protagonist' },
+ { name: 'Mr. Voss', role: 'antagonist' },
+ ]);
+ expect(merged).toHaveLength(2);
+ expect(merged.find((c) => c.name === 'Aria')?.physicalDescription).toBe('thirties, athletic, auburn hair');
+ expect(merged.every((c) => c.source === 'ai')).toBe(true);
+ });
+
+ it('preserves user edits when re-merging', async () => {
+ const id = await newWork();
+ const c = await createCharacter(id, {
+ name: 'Aria',
+ physicalDescription: 'USER VERSION — short, dark hair, scar on cheek',
+ });
+ expect(c.source).toBe('user');
+
+ const merged = await mergeExtractedCharacters(id, [{
+ name: 'aria',
+ physicalDescription: 'AI VERSION — tall, blonde',
+ personality: 'quiet, observant',
+ role: 'protagonist',
+ }]);
+ const refreshed = merged.find((x) => x.id === c.id);
+ expect(refreshed.physicalDescription).toBe('USER VERSION — short, dark hair, scar on cheek');
+ expect(refreshed.personality).toBe('quiet, observant');
+ expect(refreshed.role).toBe('protagonist');
+ });
+
+ it('matches existing character by alias when merging', async () => {
+ const id = await newWork();
+ await createCharacter(id, { name: 'Mr. Voss', aliases: ['Voss', 'The Director'], role: 'antagonist' });
+ const merged = await mergeExtractedCharacters(id, [{
+ name: 'The Director',
+ physicalDescription: 'late fifties, gray suit, bald, sharp jaw',
+ }]);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].name).toBe('Mr. Voss');
+ expect(merged[0].physicalDescription).toBe('late fifties, gray suit, bald, sharp jaw');
+ });
+
+ it('refreshes prose-derived metadata even when text fields are preserved', async () => {
+ const id = await newWork();
+ const c = await createCharacter(id, { name: 'Aria', physicalDescription: 'kept' });
+ const merged = await mergeExtractedCharacters(id, [{
+ name: 'Aria',
+ physicalDescription: 'ignored',
+ missingFromProse: ['hair color', 'eye color'],
+ evidence: ['"She walked in,"'],
+ firstAppearance: 'Chapter 1',
+ }]);
+ const updated = merged.find((x) => x.id === c.id);
+ expect(updated.physicalDescription).toBe('kept');
+ expect(updated.missingFromProse).toEqual(['hair color', 'eye color']);
+ expect(updated.firstAppearance).toBe('Chapter 1');
+ });
+});
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
index 7479fdf268..43bda2cdd9 100644
--- a/server/services/writersRoom/evaluator.js
+++ b/server/services/writersRoom/evaluator.js
@@ -15,13 +15,16 @@ import { getActiveProvider } from '../providers.js';
import { buildPrompt } from '../promptService.js';
import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';
import { getWorkWithBody } from './local.js';
+import { listCharacters, mergeExtractedCharacters } from './characters.js';
+import { nowIso, badRequest, notFound } from './_shared.js';
export { ANALYSIS_KINDS };
const KIND_META = {
- evaluate: { stage: 'writers-room-evaluate', returnsJson: true },
- format: { stage: 'writers-room-format', returnsJson: false },
- script: { stage: 'writers-room-script', returnsJson: true },
+ evaluate: { stage: 'writers-room-evaluate', returnsJson: true },
+ format: { stage: 'writers-room-format', returnsJson: false },
+ script: { stage: 'writers-room-script', returnsJson: true },
+ characters: { stage: 'writers-room-characters', returnsJson: true },
};
const ANALYSIS_ID_RE = /^wr-analysis-[0-9a-f-]+$/i;
@@ -30,10 +33,6 @@ const root = () => join(PATHS.data, 'writers-room');
const analysisDir = (workId) => join(root(), 'works', workId, 'analysis');
const analysisPath = (workId, id) => join(analysisDir(workId), `${id}.json`);
-function nowIso() { return new Date().toISOString(); }
-function badRequest(msg) { return new ServerError(msg, { status: 400, code: 'VALIDATION_ERROR' }); }
-function notFound(what) { return new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' }); }
-
// ---------- LLM invocation ----------
async function resolveProvider() {
@@ -149,6 +148,25 @@ const SHAPERS = {
suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((s) => s && typeof s === 'object') : [],
};
},
+ characters: (raw) => {
+ const parsed = extractJson(raw);
+ const list = Array.isArray(parsed.characters) ? parsed.characters : [];
+ return {
+ characters: list
+ .filter((c) => c && typeof c === 'object' && typeof c.name === 'string' && c.name.trim())
+ .map((c) => ({
+ name: c.name.trim(),
+ aliases: Array.isArray(c.aliases) ? c.aliases.filter((a) => typeof a === 'string') : [],
+ role: typeof c.role === 'string' ? c.role : '',
+ physicalDescription: typeof c.physicalDescription === 'string' ? c.physicalDescription : '',
+ personality: typeof c.personality === 'string' ? c.personality : '',
+ background: typeof c.background === 'string' ? c.background : '',
+ firstAppearance: typeof c.firstAppearance === 'string' ? c.firstAppearance : null,
+ evidence: Array.isArray(c.evidence) ? c.evidence.filter((e) => typeof e === 'string') : [],
+ missingFromProse: Array.isArray(c.missingFromProse) ? c.missingFromProse.filter((m) => typeof m === 'string') : [],
+ })),
+ };
+ },
script: (raw) => {
const parsed = extractJson(raw);
const scenes = Array.isArray(parsed.scenes) ? parsed.scenes : [];
@@ -333,15 +351,39 @@ 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.
+ 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
+ );
+ }
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;
+ if (kind === 'characters') {
+ mergedCharacters = await mergeExtractedCharacters(workId, result.characters || []);
+ }
const finished = {
...baseSnapshot,
status: 'succeeded',
providerId: usedProvider,
model: usedModel,
- result,
+ result: mergedCharacters
+ ? { ...result, mergedProfiles: mergedCharacters }
+ : result,
rawResponse: content,
completedAt: nowIso(),
};
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 97662d2e58..b18f1a2e88 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -20,6 +20,7 @@ import { readFile, rm, readdir } from 'fs/promises';
import { PATHS, atomicWrite, ensureDir, readJSONFile, safeJSONParse } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { WORK_KINDS, WORK_STATUSES } from '../../lib/writersRoomPresets.js';
+import { nowIso, badRequest, notFound } from './_shared.js';
// Paths are resolved lazily so tests can swap PATHS.data via vi.mock without
// the module-load snapshot freezing them at import time.
@@ -31,18 +32,6 @@ const worksDir = () => join(root(), 'works');
const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;
const DRAFT_ID_RE = /^wr-draft-[0-9a-f-]+$/i;
-function nowIso() {
- return new Date().toISOString();
-}
-
-function notFound(what) {
- return new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' });
-}
-
-function badRequest(message) {
- return new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });
-}
-
function workDir(workId) {
if (!WORK_ID_RE.test(workId)) throw badRequest('Invalid work id');
return join(worksDir(), workId);