Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: let Writers Room author and review the canonical character framework (#6417)
[._.]/ Adam Eivya888e12ff45d
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsxindex 06c88fc8d0..d524268747 100644--- a/client/src/components/universe/CharacterDetailEditor.jsx+++ b/client/src/components/universe/CharacterDetailEditor.jsx@@ -17,6 +17,16 @@ import {Drama, KeyRound, Mic, Images, BadgeCheck, Play, Compass,} from 'lucide-react';import { BIBLE_LIMITS as L } from '../../lib/bibleLimits';+// Shared narrative-framework definitions (#2175, #6417) — one source of truth+// with the server store/schema and the Writers Room cast editor. An+// unrecognized arc type is coerced to null server-side, so `''` = unset.+import {+ CHARACTER_ARC_TYPES,+ CHARACTER_FRAMEWORK_EDITOR_FIELDS,+ CHARACTER_MOTIVATIONS_FIELD,+ CHARACTER_SECRETS_FIELD,+ CHARACTER_SLIDER_AXES,+} from '../../lib/characterFramework';import useFieldDraft from '../../hooks/useFieldDraft';import useRowDraft from '../../hooks/useRowDraft';import usePendingListRows from '../../hooks/usePendingListRows';@@ -50,7 +60,7 @@ const SECTIONS = Object.freeze([{key: 'personality', label: 'Personality & motivations', icon: Smile,fields: [- { name: 'motivations', label: 'Motivations', placeholder: 'what they WANT and what they fear losing', max: L.MOTIVATIONS_MAX, type: 'textarea' },+ { ...CHARACTER_MOTIVATIONS_FIELD, type: 'textarea' },{ name: 'likes', label: 'Likes', placeholder: 'short prose; comma-separated', max: L.LIKES_MAX, type: 'textarea' },{ name: 'dislikes', label: 'Dislikes', placeholder: 'short prose; comma-separated', max: L.DISLIKES_MAX, type: 'textarea' },{ name: 'mannerisms', label: 'Mannerisms', placeholder: 'habitual physical / verbal tics', max: L.MANNERISMS_MAX, type: 'textarea' },@@ -60,13 +70,10 @@ const SECTIONS = Object.freeze([},{key: 'framework', label: 'Character framework', icon: Drama,- fields: [- { name: 'ghost', label: 'Ghost (backstory wound cause)', placeholder: 'the past event that wounded them — must causally explain the Lie', max: L.GHOST_MAX, type: 'textarea' },- { name: 'wound', label: 'Wound', placeholder: 'the lasting emotional damage the Ghost left', max: L.WOUND_MAX, type: 'textarea' },- { name: 'lie', label: 'Lie (optional judgment about a belief)', placeholder: 'state in one sentence — "I only matter if I win". Optional: the belief itself can live in the psychology section as a theory of control.', max: L.LIE_MAX, type: 'textarea' },- { name: 'need', label: 'Need (internal alternative)', placeholder: 'the truth that answers the Lie — "I matter whether I win or lose". It may qualify the belief rather than be its literal opposite.', max: L.NEED_MAX, type: 'textarea' },- { name: 'want', label: 'Want (external goal)', placeholder: 'the concrete goal they pursue — usually conflicts with the Need', max: L.WANT_MAX, type: 'textarea' },- ],+ // Shared with the Writers Room cast editor (#6417) — same Ghost → Wound →+ // Lie → Need → Want definitions, adapted there onto BibleSection's compact+ // field config instead of being restated.+ fields: CHARACTER_FRAMEWORK_EDITOR_FIELDS.map((f) => ({ ...f, type: 'textarea' })),},{key: 'visualIdentity', label: 'Visual identity', icon: Eye,@@ -90,11 +97,6 @@ const RELATIONSHIP_OPPOSITION_AXES = Object.freeze(['winner/loser', 'smart/dumb', 'hunter/prey', 'predator/prey', 'custom',]);-// Mirrors `CHARACTER_ARC_TYPES` in server/lib/storyBible.js (#2175). The server-// sanitizer coerces an unrecognized value to null, so an empty selection clears-// the field. `''` = unset.-const CHARACTER_ARC_TYPES = Object.freeze(['positive', 'negative', 'flat']);-const SLIDER_AXES = Object.freeze(['proactivity', 'likability', 'competence']);const VOICE_SOURCE_POLICIES = Object.freeze(['designed', 'consented-performance', 'licensed']);const IDENTITY_ASSET_ROLES = Object.freeze(['neutral', 'profile', 'full-body', 'expression-gesture', 'wardrobe',@@ -151,7 +153,7 @@ const LIST_SECTIONS = Object.freeze([// via `toRows` / `fromRows` below (see ListSectionEditor).stringList: true,columns: [- { name: 'text', placeholder: 'something they hide from others or themselves', max: L.SECRET_MAX },+ { name: 'text', placeholder: CHARACTER_SECRETS_FIELD.placeholder, max: CHARACTER_SECRETS_FIELD.max },],summary: (s) => s.text,},@@ -546,7 +548,7 @@ function ArcFrameworkControls({ entry, onPatch, disabled, idPrefix }) {const sliders = (entry.sliders && typeof entry.sliders === 'object') ? entry.sliders : {};const arcId = `chr-arc-${idPrefix || 'unknown'}`;const patchSlider = (axis, value) => onPatch?.({ sliders: { ...sliders, [axis]: value } });- const setCount = SLIDER_AXES.reduce((n, a) => n + (typeof entry[a] === 'string' ? 0 : (sliders[a] != null ? 1 : 0)), 0);+ const setCount = CHARACTER_SLIDER_AXES.reduce((n, a) => n + (typeof entry[a] === 'string' ? 0 : (sliders[a] != null ? 1 : 0)), 0);const summary = `${entry.arcType || 'no arc'}${setCount ? ` · ${setCount}/3 sliders` : ''}`;return (<BoxedSection icon={Drama} label="Arc type & sliders" summary={summary}>@@ -568,7 +570,7 @@ function ArcFrameworkControls({ entry, onPatch, disabled, idPrefix }) {<p className="text-[10px] text-gray-500 leading-snug">Rule: HIGH (≥7) on at least two sliders, or high on one with room to grow. All-low = boring; all-high = Mary Sue.</p>- {SLIDER_AXES.map((axis) => {+ {CHARACTER_SLIDER_AXES.map((axis) => {const id = `chr-slider-${idPrefix || 'unknown'}-${axis}`;const val = sliders[axis];const set = val != null;diff --git a/client/src/components/writers-room/BibleSection.jsx b/client/src/components/writers-room/BibleSection.jsxindex 5775e93c26..984ef3c529 100644--- a/client/src/components/writers-room/BibleSection.jsx+++ b/client/src/components/writers-room/BibleSection.jsx@@ -20,8 +20,13 @@ import useMounted from '../../hooks/useMounted';// editButtonTitle — title="" on the row's edit button// primary: { key, label, placeholder, inputExtraClass, autoFocus, trim }// — the bare identity input (object/character name, place slugline)-// fields: [{ key, label, placeholder, kind: 'text'|'csv'|'multiline', rows, trim }]-// — every other editable field, rendered in order in the Editor+// fields: [{ key, label, placeholder, kind, rows, trim, options, heading }]+// — every other editable field, rendered in order in the Editor.+// kind: 'text' (input) | 'multiline' (textarea) | 'csv' (comma-separated+// → string[]) | 'lines' (one entry per line → string[], for a list the+// entries are long enough to want their own row) | 'select' (a <select>+// over `options: [{ value, label }]`, persisting '' as null so the field+// can be cleared). `heading` renders a small group label above the field.// bodyField, bodyEmptyText — the row's primary description line// detailBlocks: [{ key, label, marginClass }] — extra "Label: value" lines// blanksExcludeKeys — fields skipped by the "Missing: …" warning@@ -31,6 +36,11 @@ import useMounted from '../../hooks/useMounted';// getSortKey(item) — list sort comparator key// validate(draft) — returns an error string, or null// api: { list, create, update, remove }+// Marshal a `csv` / `lines` textarea back to the string[] the API stores.+// An empty box yields `[]` — a real clear, not an omitted key.+const splitEntries = (raw, separator) =>+ String(raw || '').split(separator).map((s) => s.trim()).filter(Boolean);+export function BibleAiBadge() {return (<span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">@@ -205,7 +215,9 @@ function BibleEditor({ workId, item, config, onSaved, onDeleted, onCancel }) {const [draft, setDraft] = useState(() => {const seed = { [primary.key]: item?.[primary.key] || '' };for (const f of fields) {- seed[f.key] = f.kind === 'csv' ? (item?.[f.key] || []).join(', ') : (item?.[f.key] || '');+ if (f.kind === 'csv') seed[f.key] = (item?.[f.key] || []).join(', ');+ else if (f.kind === 'lines') seed[f.key] = (item?.[f.key] || []).join('\n');+ else seed[f.key] = item?.[f.key] || '';}return seed;});@@ -221,10 +233,14 @@ function BibleEditor({ workId, item, config, onSaved, onDeleted, onCancel }) {}setSaving(true);const payload = { [primary.key]: draft[primary.key].trim() };+ // Every field is always sent, including as its empty value — '' / [] /+ // null is how the writer CLEARS one, and the server distinguishes that+ // from an absent key (which would preserve the stored value).for (const f of fields) {- payload[f.key] = f.kind === 'csv'- ? draft[f.key].split(',').map((s) => s.trim()).filter(Boolean)- : (f.trim ? draft[f.key].trim() : draft[f.key]);+ if (f.kind === 'csv') payload[f.key] = splitEntries(draft[f.key], ',');+ else if (f.kind === 'lines') payload[f.key] = splitEntries(draft[f.key], '\n');+ else if (f.kind === 'select') payload[f.key] = draft[f.key] || null;+ else payload[f.key] = f.trim ? draft[f.key].trim() : draft[f.key];}const result = await (isCreate? config.api.create(workId, payload, { silent: true })@@ -278,14 +294,26 @@ function BibleEditor({ workId, item, config, onSaved, onDeleted, onCancel }) {</button></div>{fields.map((f) => (- <label key={f.key} htmlFor={`bible-field-${f.key}`} className="block">- <span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>- {f.kind === 'multiline' ? (- <textarea id={`bible-field-${f.key}`} value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} rows={f.rows || 2} className={`${inputCls} font-sans resize-y`} />- ) : (- <input id={`bible-field-${f.key}`} value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} className={inputCls} />+ <div key={f.key}>+ {f.heading && (+ <div className="text-[9px] uppercase tracking-wider text-port-accent/80 pt-1.5 pb-0.5 border-t border-port-border/60 mt-1.5">+ {f.heading}+ </div>)}- </label>+ <label htmlFor={`bible-field-${f.key}`} className="block">+ <span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>+ {f.kind === 'multiline' || f.kind === 'lines' ? (+ <textarea id={`bible-field-${f.key}`} value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} rows={f.rows || 2} className={`${inputCls} font-sans resize-y`} />+ ) : f.kind === 'select' ? (+ <select id={`bible-field-${f.key}`} value={draft[f.key]} onChange={set(f.key)} className={inputCls}>+ <option value="">{f.placeholder || '—'}</option>+ {(f.options || []).map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}+ </select>+ ) : (+ <input id={`bible-field-${f.key}`} value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} className={inputCls} />+ )}+ </label>+ </div>))}<div className="flex items-center justify-between pt-1">{!isCreate ? (diff --git a/client/src/components/writers-room/BibleSection.test.jsx b/client/src/components/writers-room/BibleSection.test.jsxindex 8cab354931..7de1e5afcf 100644--- a/client/src/components/writers-room/BibleSection.test.jsx+++ b/client/src/components/writers-room/BibleSection.test.jsx@@ -124,7 +124,10 @@ const SCENARIOS = [personality: '', background: '', notes: '', source: 'user',},createPrimaryValue: 'Bly',- createPayload: { name: 'Bly', aliases: [], role: '', physicalDescription: '', personality: '', background: '', notes: '' },+ createPayload: {+ name: 'Bly', aliases: [], role: '', physicalDescription: '', personality: '', background: '', notes: '',+ motivations: '', ghost: '', wound: '', lie: '', need: '', want: '', arcType: null, secrets: [],+ },createdRecord: {id: 'char-2', name: 'Bly', aliases: [], role: '', physicalDescription: '', personality: '',background: '', notes: '', source: 'user',@@ -135,6 +138,7 @@ const SCENARIOS = [updatePayload: {name: 'Ada', aliases: [], role: 'protagonist', physicalDescription: 'Short, silver hair, sharp eyes.',personality: '', background: '', notes: '',+ motivations: '', ghost: '', wound: '', lie: '', need: '', want: '', arcType: null, secrets: [],},},];diff --git a/client/src/components/writers-room/CharactersBible.framework.test.jsx b/client/src/components/writers-room/CharactersBible.framework.test.jsxnew file mode 100644index 0000000000..0e9fb78ae7--- /dev/null+++ b/client/src/components/writers-room/CharactersBible.framework.test.jsx@@ -0,0 +1,111 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, cleanup, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../services/apiWritersRoom', () => ({+ listWritersRoomCharacters: vi.fn(),+ createWritersRoomCharacter: vi.fn(),+ updateWritersRoomCharacter: vi.fn(),+ deleteWritersRoomCharacter: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },+}));++import CharactersBible from './CharactersBible';+import {+ listWritersRoomCharacters,+ updateWritersRoomCharacter,+} from '../../services/apiWritersRoom';++// Obviously-fake fixture — never a record from a live instance.+const CHARACTER = {+ id: 'wr-char-1',+ name: 'Wren Calloway',+ aliases: [],+ role: 'protagonist',+ physicalDescription: 'Short, silver hair, sharp eyes.',+ personality: '',+ background: '',+ notes: '',+ motivations: '',+ ghost: 'Left behind at the relay station at nine.',+ wound: '',+ lie: '',+ need: '',+ want: '',+ arcType: null,+ secrets: [],+ source: 'user',+};++beforeEach(() => { vi.clearAllMocks(); });+afterEach(() => { cleanup(); });++describe('CharactersBible — narrative framework editing (#6417)', () => {+ it('edits the belief and the internal need, then shows them after a reload', async () => {+ const LIE = 'I only matter while I am useful.';+ const NEED = 'Being wanted is not the same as being needed.';+ const saved = { ...CHARACTER, lie: LIE, need: NEED };+ listWritersRoomCharacters.mockResolvedValue([CHARACTER]);+ updateWritersRoomCharacter.mockResolvedValue(saved);++ const { unmount } = render(<CharactersBible workId="wr-work-1" />);+ await screen.findByText('Wren Calloway');++ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));+ await userEvent.type(screen.getByLabelText(/^Lie/), LIE);+ await userEvent.type(screen.getByLabelText(/^Need/), NEED);+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());+ const [workId, characterId, payload] = updateWritersRoomCharacter.mock.calls[0];+ expect(workId).toBe('wr-work-1');+ expect(characterId).toBe('wr-char-1');+ expect(payload).toMatchObject({ lie: LIE, need: NEED });+ // Untouched framework fields ride along as their empty value so the server+ // sees an explicit state, and the authored Ghost is preserved verbatim.+ expect(payload.ghost).toBe(CHARACTER.ghost);+ expect(payload.arcType).toBeNull();+ expect(payload.secrets).toEqual([]);++ // Reload: a fresh mount refetches and renders what the server persisted.+ unmount();+ listWritersRoomCharacters.mockResolvedValue([saved]);+ render(<CharactersBible workId="wr-work-1" />);++ await screen.findByText(NEED);+ await userEvent.click(await screen.findByRole('button', { name: 'Edit Wren Calloway' }));+ expect(screen.getByLabelText(/^Lie/)).toHaveValue(LIE);+ expect(screen.getByLabelText(/^Need/)).toHaveValue(NEED);+ });++ it('sends an arc type and one secret per line, and clears them back to empty', async () => {+ listWritersRoomCharacters.mockResolvedValue([CHARACTER]);+ updateWritersRoomCharacter.mockImplementation(async (_w, _id, patch) => ({ ...CHARACTER, ...patch }));++ render(<CharactersBible workId="wr-work-1" />);+ await screen.findByText('Wren Calloway');++ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));+ await userEvent.selectOptions(screen.getByLabelText('Arc type'), 'positive');+ await userEvent.type(screen.getByLabelText(/^Secrets/), 'Sold the license\nCannot read the old charts');+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalledTimes(1));+ expect(updateWritersRoomCharacter.mock.calls[0][2]).toMatchObject({+ arcType: 'positive',+ secrets: ['Sold the license', 'Cannot read the old charts'],+ });++ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));+ await userEvent.selectOptions(screen.getByLabelText('Arc type'), '');+ await userEvent.clear(screen.getByLabelText(/^Secrets/));+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalledTimes(2));+ // A cleared select/list is `null` / `[]` — present and empty, which is how+ // the server tells a deliberate clear from an untouched field.+ expect(updateWritersRoomCharacter.mock.calls[1][2]).toMatchObject({ arcType: null, secrets: [] });+ });+});diff --git a/client/src/components/writers-room/CharactersBible.jsx b/client/src/components/writers-room/CharactersBible.jsxindex 948445043d..d6aacf981b 100644--- a/client/src/components/writers-room/CharactersBible.jsx+++ b/client/src/components/writers-room/CharactersBible.jsx@@ -1,4 +1,10 @@import BibleSection, { BibleAiBadge } from './BibleSection';+import {+ CHARACTER_ARC_TYPES,+ CHARACTER_FRAMEWORK_EDITOR_FIELDS,+ CHARACTER_MOTIVATIONS_FIELD,+ CHARACTER_SECRETS_FIELD,+} from '../../lib/characterFramework';import {listWritersRoomCharacters,createWritersRoomCharacter,@@ -6,6 +12,32 @@ import {deleteWritersRoomCharacter,} from '../../services/apiWritersRoom';+// Adapter over the shared narrative-framework definitions (#6417): the same+// Ghost → Wound → Lie → Need → Want copy the Universe cast editor renders,+// mapped onto BibleSection's compact field config. Deliberately NOT a copy of+// the universe editor — the media / voice / identity-pack surfaces stay there.+const ARC_TYPE_HINTS = Object.freeze({+ positive: 'positive — overcomes the Lie',+ negative: 'negative — consumed by the Lie',+ flat: 'flat — holds the truth, changes the world',+});+const FRAMEWORK_FIELDS = [+ { key: CHARACTER_MOTIVATIONS_FIELD.name, label: CHARACTER_MOTIVATIONS_FIELD.label, placeholder: CHARACTER_MOTIVATIONS_FIELD.placeholder, kind: 'multiline', rows: 2, heading: 'Character framework' },+ ...CHARACTER_FRAMEWORK_EDITOR_FIELDS.map((f) => ({ key: f.name, label: f.label, placeholder: f.placeholder, kind: 'multiline', rows: 2 })),+ {+ key: 'arcType',+ label: 'Arc type',+ placeholder: 'unset',+ kind: 'select',+ options: CHARACTER_ARC_TYPES.map((value) => ({ value, label: ARC_TYPE_HINTS[value] || value })),+ },+ { key: CHARACTER_SECRETS_FIELD.name, label: `${CHARACTER_SECRETS_FIELD.label} (one per line)`, placeholder: CHARACTER_SECRETS_FIELD.placeholder, kind: 'lines', rows: 3 },+];+// The framework is optional by design — a character with no Ghost isn't+// incomplete — so it stays out of the row's "Missing: …" warning, which+// exists to flag the render-critical fields.+const FRAMEWORK_KEYS = FRAMEWORK_FIELDS.map((f) => f.key);+const CHARACTER_CONFIG = {icon: null,countLabel: (n) => `${n} character${n === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.`,@@ -24,11 +56,15 @@ const CHARACTER_CONFIG = {{ key: 'personality', label: 'Personality', placeholder: 'Temperament, voice, quirks', kind: 'multiline', rows: 2 },{ key: 'background', label: 'Background', placeholder: 'Who they are, where they come from', kind: 'multiline', rows: 2 },{ key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },+ ...FRAMEWORK_FIELDS,],bodyField: 'physicalDescription',bodyEmptyText: 'No physical description — image gen will use scene context only',- detailBlocks: [],- blanksExcludeKeys: ['notes', 'aliases'],+ detailBlocks: [+ { key: 'want', label: 'Want', marginClass: 'mt-1' },+ { key: 'need', label: 'Need', marginClass: '' },+ ],+ blanksExcludeKeys: ['notes', 'aliases', ...FRAMEWORK_KEYS],renderTitle: (item, { light }) => (<span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{item.name}</span>),diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex b22360f2b8..9eb968e395 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -51,6 +51,7 @@ grep -i "what you want to do" client/src/lib/README.md| `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. || `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. || `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |+| `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, and `CHARACTER_SLIDER_AXES`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). || `catalogTypes.js` | The catalog ingredient type registry as the UI consumes it. `CATALOG_TYPES` is PROJECTED from `server/lib/catalogTypes.js` (label, badge color, primary-content key/label, snippet fallback chain, `editableListFields` and its `BIBLE_LIMITS` caps) and decorated with the client-only editor layout (`editorSections` / `editorFields`); `RELATION_KINDS`, `MEDIA_KINDS`, `canonicalTagKey`, `payloadSnippet`, `USER_TYPE_FIELD_KINDS` are re-exported outright. Also the badge/ref-role lookups and the user-defined-type normalization `useCatalogTypes` merges in. || `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. || `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |diff --git a/client/src/lib/characterFramework.js b/client/src/lib/characterFramework.jsnew file mode 100644index 0000000000..68e995d17f--- /dev/null+++ b/client/src/lib/characterFramework.js@@ -0,0 +1,63 @@+/**+ * Shared narrative-character framework definitions for the client editors.+ *+ * Re-exports the canonical field list from the pure server leaf+ * `server/lib/characterFramework.js` (so the store's `editableFields`, the+ * route Zod schemas and the UI can never drift apart) and adds the editor-only+ * descriptors — label, placeholder, and per-field cap — that both cast editors+ * render:+ *+ * - `client/src/components/universe/CharacterDetailEditor.jsx` (Universe Bible)+ * - `client/src/components/writers-room/CharactersBible.jsx` (Writers Room),+ * which adapts these descriptors onto the compact `BibleSection` field+ * config rather than mounting the full universe media/voice editor.+ */+import {+ CHARACTER_ARC_TYPES,+ CHARACTER_FRAMEWORK_FIELDS,+ CHARACTER_FRAMEWORK_LIMITS,+ CHARACTER_FRAMEWORK_TEXT_FIELDS,+} from '../../../server/lib/characterFramework.js';+import { BIBLE_LIMITS } from './bibleLimits.js';++export {+ CHARACTER_ARC_TYPES,+ CHARACTER_FRAMEWORK_FIELDS,+ CHARACTER_FRAMEWORK_LIMITS,+ CHARACTER_FRAMEWORK_TEXT_FIELDS,+};++// The Three Sliders axes (#2175). Mirrors `sanitizeCharacterSliders` in+// server/lib/storyBible.js — an unset axis is null, never 0.+export const CHARACTER_SLIDER_AXES = Object.freeze(['proactivity', 'likability', 'competence']);++// What the writer WANTS and fears losing. Authored beside the framework but+// stored as its own long-form field; the Universe editor renders it in its+// "Personality & motivations" section, Writers Room above the Ghost.+export const CHARACTER_MOTIVATIONS_FIELD = Object.freeze({+ name: 'motivations',+ label: 'Motivations',+ placeholder: 'what they WANT and what they fear losing',+ max: CHARACTER_FRAMEWORK_LIMITS.motivations,+});++// Ghost → Wound → Lie → Need → Want, in authoring order. The Lie is a JUDGMENT+// about a belief and stays optional; the Need may qualify that belief rather+// than be its literal opposite (see the psychology notes in storyBible.js).+export const CHARACTER_FRAMEWORK_EDITOR_FIELDS = Object.freeze([+ { name: 'ghost', label: 'Ghost (backstory wound cause)', placeholder: 'the past event that wounded them — must causally explain the Lie', max: CHARACTER_FRAMEWORK_LIMITS.ghost },+ { name: 'wound', label: 'Wound', placeholder: 'the lasting emotional damage the Ghost left', max: CHARACTER_FRAMEWORK_LIMITS.wound },+ { name: 'lie', label: 'Lie (optional judgment about a belief)', placeholder: 'state in one sentence — "I only matter if I win". Optional: the belief itself can live in the psychology section as a theory of control.', max: CHARACTER_FRAMEWORK_LIMITS.lie },+ { name: 'need', label: 'Need (internal alternative)', placeholder: 'the truth that answers the Lie — "I matter whether I win or lose". It may qualify the belief rather than be its literal opposite.', max: CHARACTER_FRAMEWORK_LIMITS.need },+ { name: 'want', label: 'Want (external goal)', placeholder: 'the concrete goal they pursue — usually conflicts with the Need', max: CHARACTER_FRAMEWORK_LIMITS.want },+]);++// Secrets are a plain string[] on the server (`cleanStringArray`), so an+// editor marshals them per row / per line rather than as prose.+export const CHARACTER_SECRETS_FIELD = Object.freeze({+ name: 'secrets',+ label: 'Secrets',+ placeholder: 'something they hide from others or themselves',+ max: BIBLE_LIMITS.SECRET_MAX,+ maxItems: BIBLE_LIMITS.SECRETS_PER_CHARACTER_MAX,+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex d0d8836820..9554b2d039 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -25,6 +25,7 @@ export * from './autopilotMilestones.js';export * from './beatColors.js';export * from './beatGrid.js';export * from './bibleLimits.js';+export * from './characterFramework.js';export * from './catalogTypes.js';export * from './creativeDirectorPlan.js';export * from './creativeDirectorPreview.js';diff --git a/data.reference/prompts/stages/writers-room-characters.md b/data.reference/prompts/stages/writers-room-characters.mdindex 71a7986acc..48799e6dfb 100644--- a/data.reference/prompts/stages/writers-room-characters.md+++ b/data.reference/prompts/stages/writers-room-characters.md@@ -36,9 +36,21 @@ For every named character (or distinct unnamed character — "the bartender", "t- `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.+2. **Propose narrative framework ONLY where the prose supports it.** These fields describe the character's interior, and a wrong guess is worse than a gap — unlike `physicalDescription`, nothing downstream breaks when they stay empty. Emit a field only when the prose gives you something concrete to point at, and leave it out entirely otherwise:+ - `motivations` — what they are visibly pursuing and what they fear losing.+ - `ghost` — the past event the prose establishes as the source of their damage.+ - `wound` — the lasting damage that event left.+ - `lie` — the false belief they act on, in one sentence ("I only matter if I win").+ - `need` — the truth that answers the Lie; it may qualify the belief rather than invert it.+ - `want` — the concrete external goal they chase, usually in tension with the Need.+ - `arcType` — `positive` (overcomes the Lie), `negative` (consumed by it), or `flat` (already holds the truth and changes the world instead). Omit unless the draft actually shows the shape.+ - `secrets` — things they hide from others or from themselves, one per entry.-3. **Visually differentiate every character in the cast.** Before finalizing, scan all `physicalDescription` values you're producing AND every non-empty `physicalDescription` in the existing profiles above. **No two characters may be visually interchangeable** — if you produce two adult women in dark jackets with brown hair, an image model will render them as the same person. Pick distinguishing choices across:+ **Do not invent a backstory to fill these in.** An empty framework field is a correct answer for a character the prose has not opened up; a fabricated Ghost silently becomes canon the writer then has to argue with. When you propose one from indirect evidence rather than something stated on the page, add the field name to `missingFromProse` (e.g. `ghost`, `lie`) so the writer can see which reads are inference. The rule in step 5 about committing to a renderable detail applies to `physicalDescription` alone — never to the framework.++3. **Respect existing edits.** If a field in the existing profile is already filled in, keep that value verbatim. Only populate empty / missing fields. This applies to every framework field above: a Ghost, Lie, Want, Need, arc type, or secret the writer has already authored is authoritative even when the prose seems to contradict it.++4. **Visually differentiate every character in the cast.** Before finalizing, scan all `physicalDescription` values you're producing AND every non-empty `physicalDescription` in the existing profiles above. **No two characters may be visually interchangeable** — if you produce two adult women in dark jackets with brown hair, an image model will render them as the same person. Pick distinguishing choices across:- ethnicity / heritage (e.g. East Asian, Afro-Caribbean, Mediterranean, Pacific Islander, Nordic — be specific, not generic "white" or "diverse")- age decade (mid-20s vs late-30s vs 50s reads completely different)- hair (color, length, texture, style — don't give two characters the same dark bob)@@ -46,13 +58,13 @@ For every named character (or distinct unnamed character — "the bartender", "t- signature garment + palette (one character's "rumpled jacket" should not collide with another's)When two characters would otherwise collide on a dimension, deliberately push one in a different direction.-4. **Commit when prose is silent, then log it.** When the prose doesn't specify a renderable detail (hair color, ethnicity, exact wardrobe), DO NOT leave `physicalDescription` blank on that axis — pick a specific, opinionated choice that fits the character's role and differentiates them from the rest of the cast. Then list the field path in `missingFromProse` (e.g. `physicalDescription.hairColor`) so the writer knows you committed without prose evidence and can override if needed. The bible drives image gen — empty axes produce identical-looking characters. A committed-but-flagged choice is always better than a gap.+5. **Commit when prose is silent, then log it.** When the prose doesn't specify a renderable detail (hair color, ethnicity, exact wardrobe), DO NOT leave `physicalDescription` blank on that axis — pick a specific, opinionated choice that fits the character's role and differentiates them from the rest of the cast. Then list the field path in `missingFromProse` (e.g. `physicalDescription.hairColor`) so the writer knows you committed without prose evidence and can override if needed. The bible drives image gen — empty axes produce identical-looking characters. A committed-but-flagged choice is always better than a gap.-5. Do not include characters who are merely referenced (e.g. "her dead father") unless they appear in a scene. Use your judgment.+6. 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:+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. The framework keys (`motivations` through `secrets`) are OPTIONAL: omit any the prose does not support rather than emitting an empty or invented value.```json{@@ -64,9 +76,17 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"physicalDescription": "string","personality": "string","background": "string",+ "motivations": "string",+ "ghost": "string",+ "wound": "string",+ "lie": "string",+ "need": "string",+ "want": "string",+ "arcType": "positive|negative|flat",+ "secrets": ["string", ...],"firstAppearance": "string or null","evidence": ["string", ...],- "missingFromProse": ["physicalDescription.hair", "physicalDescription.eyes", "background", ...]+ "missingFromProse": ["physicalDescription.hair", "physicalDescription.eyes", "ghost", ...]}]}diff --git a/data.reference/prompts/stages/writers-room-evaluate.md b/data.reference/prompts/stages/writers-room-evaluate.mdindex 15a83751f3..bdac26dbe4 100644--- a/data.reference/prompts/stages/writers-room-evaluate.md+++ b/data.reference/prompts/stages/writers-room-evaluate.md@@ -15,6 +15,18 @@ You are an editorial reader giving a single round of constructive feedback on a{{draftBody}}```+{{#castFrameworkJson}}+## Authored character framework++The writer has already declared the following for this cast — their motivations, the Ghost that wounded them, the Wound itself, the Lie they believe, the Need that answers it, the Want they chase, the arc they intend, and the secrets they keep. This is the PLAN, not a description of the draft.++```json+{{castFrameworkJson}}+```++Use it only to judge delivery against intent: where the prose earns a declared beat, and where a declared Lie / Need / arc is asserted in the bible but never dramatized on the page. Do not restate the plan back as a strength, do not treat a field the writer left blank as a defect, and do not invent framework the writer has not declared. Character issues that reference the plan belong in `issues` with `category: "character"`, anchored to a real `excerpt` like every other issue.+{{/castFrameworkJson}}+## TaskRead the entire draft. Then produce one editorial pass that covers:diff --git a/docs/features/writers-room.md b/docs/features/writers-room.mdindex 6e2161a16e..a8f3862e8b 100644--- a/docs/features/writers-room.md+++ b/docs/features/writers-room.md@@ -53,6 +53,8 @@ Each draft version records `id`, `label`, `contentFile`, `contentHash`, `wordCouCharacters, places, and objects extracted by analysis (or entered by hand) live as per-work bible entities with full CRUD (`characters.js` / `places.js` / `objects.js`; client `CharactersBible.jsx`, `PlacesBible.jsx`, `ObjectsBible.jsx`, `StoryboardBibleTab.jsx`). Extraction merges into existing entries rather than duplicating.+A character carries the same narrative framework the Universe Bible stores — motivations, Ghost → Wound → Lie → Need → Want, the declared arc type, secrets, and structured relationship links — from one definition in `server/lib/characterFramework.js` (mirrored for the editors by `client/src/lib/characterFramework.js`), so the store's editable fields, the route schemas, and both cast editors cannot drift. Every field is optional, and clearing one (`''` / `[]` / `null`) is a real authored state, distinct from omitting the key. Prose extraction may PROPOSE framework values but never overwrites an authored one, and the author-side `evaluate` pass receives the cast's framework so it reports delivery against the writer's plan rather than inferring both from the same draft. Promotion to the Pipeline copies the whole framework — including `wr-char-` ids, so relationship links still resolve inside the minted universe.+## Storyboard & MediaThe storyboard suite (`StoryboardPanel.jsx`, `StoryboardScenesTab.jsx`, `StoryboardBoardsTab.jsx`, `StoryboardConfigTab.jsx`, `SceneCard.jsx`) turns script-analysis scenes into rendered boards through the existing image-gen pipeline and media job queue. When the Adapt flow completes, the panel auto-queues a render for every scene that doesn't have an image yet — one Adapt click implies the whole board's image cost. Scene images ride the shared media-collection infrastructure — a work auto-creates its collection on first render.diff --git a/scripts/migrations/362-writers-room-character-framework.js b/scripts/migrations/362-writers-room-character-framework.jsnew file mode 100644index 0000000000..e66eaa8a89--- /dev/null+++ b/scripts/migrations/362-writers-room-character-framework.js@@ -0,0 +1,33 @@+/**+ * Teach the two Writers Room character-facing prompts the narrative framework+ * the bible has always been able to store (#6417):+ *+ * - `writers-room-characters.md` may now PROPOSE motivations / Ghost / Wound /+ * Lie / Need / Want / arc type / secrets, under an explicit rule that an+ * empty framework field beats an invented backstory and that an inferred+ * read is flagged in `missingFromProse`.+ * - `writers-room-evaluate.md` receives the authored framework (when the work+ * has one) so the editorial pass reports delivery against the writer's plan+ * instead of inferring the plan and the delivery from the same prose.+ */+import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ "writers-room-characters.md": [+ "cdd99c7a3ef92bf798f30fa2fb4465f1"+ ],+ "writers-room-evaluate.md": [+ "d3374472820df264731f435141e05270"+ ]+};+export const NEW_SHIPPED_MD5 = {+ "writers-room-characters.md": "4b19f6538ff3a602007ef8e32c8e5047",+ "writers-room-evaluate.md": "d3b2b40bcabc9ca690fa67b69d64d628"+};+const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,+ label: 'writers-room character framework',+ customizedHint: (filename) => ` Merge the character-framework guidance (Ghost / Wound / Lie / Need / Want, arc type, secrets) and its output keys from data.reference/prompts/stages/${filename}.`,+});+export { applyMigration };+export default { up };diff --git a/scripts/migrations/362-writers-room-character-framework.test.js b/scripts/migrations/362-writers-room-character-framework.test.jsnew file mode 100644index 0000000000..d30b117886--- /dev/null+++ b/scripts/migrations/362-writers-room-character-framework.test.js@@ -0,0 +1,6 @@+import { describe } from 'vitest';+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './362-writers-room-character-framework.js';+import { runPromptMigrationTests } from './_testHelpers.js';+describe('migration 362 — writers-room character framework prompts', () => {+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-362-' });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex a8ed1341ae..dc9319d213 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -38,6 +38,8 @@ const EXPECTED_STAGE_OLD = {'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],+ 'writers-room-characters.md': ['cdd99c7a3ef92bf798f30fa2fb4465f1'],+ 'writers-room-evaluate.md': ['d3374472820df264731f435141e05270'],'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139', '67b6e73ed47f318451a730088b4cff14', '177b6e4e8bdf445308cf8ac423cd5ad8', '924fe8836f3014873d1789e98e997db2'],'story-builder-idea-expand.md': ['778c86e2caa120856c36e4d5a4da3355', 'a23939626a226f7420cebfb45d47950c'],'pipeline-editorial-analysis.md': ['14d9879697c66d51830cc798040d5369'],@@ -82,6 +84,8 @@ const EXPECTED_STAGE_NEW = {'pipeline-script-verify.md': '722c62462d05462603cf67ca0ed1dee8','pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',+ 'writers-room-characters.md': '4b19f6538ff3a602007ef8e32c8e5047',+ 'writers-room-evaluate.md': 'd3b2b40bcabc9ca690fa67b69d64d628','cos-agent-briefing.md': 'a01c81d3a7f4ac0ca9e8d5137735c0e3','universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd','story-builder-idea-expand.md': 'c12d76fefaaded2838023065bfc94bb0',diff --git a/server/lib/README.md b/server/lib/README.mdindex 6eb004ac88..928b132008 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -110,6 +110,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `editorial/` | Extensible editorial-check registry (#1284) — `EDITORIAL_CHECKS` + fail-fast guards + lookup/state helpers. See `editorial/README.md`. The runner that executes checks lives at `server/services/pipeline/editorial/checkRunner.js`. || `fableLoomGraph.js` | FableLoom branching-narrative graph analysis: `analyzeEpisodeGraph` (deterministic validation — reachability, dead ends, dangling paths, intent hygiene), `computeGraphLayers` (BFS layering), `describeGraphForPrompt` (compact text rendering for LLM stages), `GRAPH_ISSUE_CODES`. || `storyBible.js` | Canonical Character / Place / Object shapes; re-exports `BIBLE_LIMITS` from `bibleLimits.js`. Also the reveal-gated canon / spoiler-scoping helpers (#2178): `filterCanonForIssue` / `filterCanonListForIssue` / `isCanonEntryGatedForIssue` (hide or surface-substitute a gated entry in a drafting prompt), `canonHasRevealGated` + `revealGatedCanonRows` (for the `continuity.premature-reveal` check gate/summary). |+| `characterFramework.js` | The narrative-character framework as one definition: `CHARACTER_ARC_TYPES`, `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_FIELDS` (the Ghost→Wound→Lie→Need→Want chain plus motivations, arc type, secrets, relationship links), `CHARACTER_FRAMEWORK_LIMITS`, and `pickCharacterFramework` / `pickCastFramework` (framework-only projection for an author-side review prompt, empty entries dropped). A pure leaf over `bibleLimits.js` so the store editableFields, the Zod schemas, and the client editors share one list (#6417). || `bibleLimits.js` | `BIBLE_LIMITS` — the canon field length/count caps every story-bible sanitizer, Zod schema, and catalog payload upgrade measures against. A pure leaf split out of `storyBible.js` (which pulls `crypto` + `fileUtils`) so `catalogTypes.js` and the browser bundle can read the numbers alone. || `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. || `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. |diff --git a/server/lib/characterFramework.js b/server/lib/characterFramework.jsnew file mode 100644index 0000000000..92ddb913a6--- /dev/null+++ b/server/lib/characterFramework.js@@ -0,0 +1,91 @@+/**+ * Canonical narrative-character framework field list — the Ghost → Wound →+ * Lie → Want → Need chain plus the declared arc type, secrets, motivations,+ * and structured relationship links.+ *+ * A PURE LEAF (imports only `bibleLimits.js`) so three otherwise-unrelated+ * consumers can share one definition instead of three hand-mirrored copies:+ *+ * - `server/lib/storyBible.js` — re-exports `CHARACTER_ARC_TYPES`+ * - `server/services/writersRoom/characters.js` — store `editableFields`+ * - `client/src/lib/characterFramework.js` — the editor field descriptors+ * rendered by both the Universe cast editor and the Writers Room bible+ *+ * Everything here is OPTIONAL on a character. A blank string / null / empty+ * array is the legacy shape, and clearing a field is a real authored action —+ * never treat "absent" and "present but empty" as the same thing (see the+ * absent-vs-intentionally-empty rule in AGENTS.md).+ */++import { BIBLE_LIMITS } from './bibleLimits.js';++// Declared character arc type (#2175). A positive arc overcomes the Lie and+// embraces the Truth; a negative arc is consumed by the Lie; a flat arc holds+// a truth the character already knows and changes the world around them+// instead. Unset (null) keeps the field absent for every pre-#2175 record.+// Defined here rather than in `storyBible.js` so the browser bundle can read+// the list without pulling `crypto` + `fileUtils`; `storyBible.js` re-exports+// it so every existing importer keeps working.+export const CHARACTER_ARC_TYPES = Object.freeze(['positive', 'negative', 'flat']);++// The prose half of the framework, in authoring order: what they pursue, the+// origin damage, the belief it produced, and the two competing resolutions.+export const CHARACTER_FRAMEWORK_TEXT_FIELDS = Object.freeze([+ 'motivations', 'ghost', 'wound', 'lie', 'need', 'want',+]);++// Per-field caps, keyed by field name, so a Zod schema or an editor can size+// its inputs without re-deriving the `<FIELD>_MAX` naming convention.+export const CHARACTER_FRAMEWORK_LIMITS = Object.freeze({+ motivations: BIBLE_LIMITS.MOTIVATIONS_MAX,+ ghost: BIBLE_LIMITS.GHOST_MAX,+ wound: BIBLE_LIMITS.WOUND_MAX,+ lie: BIBLE_LIMITS.LIE_MAX,+ need: BIBLE_LIMITS.NEED_MAX,+ want: BIBLE_LIMITS.WANT_MAX,+});++// Every framework field a writer may author, prose + structured. `secrets` is+// a plain string[]; `relationshipLinks` is the structured character↔character+// link list (#1287); `arcType` is one of CHARACTER_ARC_TYPES or null.+export const CHARACTER_FRAMEWORK_FIELDS = Object.freeze([+ ...CHARACTER_FRAMEWORK_TEXT_FIELDS,+ 'arcType', 'secrets', 'relationshipLinks',+]);++// Projection used to hand an author-side review the framework it is supposed+// to judge delivery against, without shipping the render-oriented half of the+// profile (physical description, image refs, wardrobes, voice). Entries with+// nothing authored are dropped so an unfilled cast contributes no prompt text+// at all rather than a page of empty keys.+export function pickCharacterFramework(entry) {+ if (!entry || typeof entry !== 'object') return null;+ const out = { name: typeof entry.name === 'string' ? entry.name : '' };+ for (const field of CHARACTER_FRAMEWORK_TEXT_FIELDS) {+ const value = typeof entry[field] === 'string' ? entry[field].trim() : '';+ if (value) out[field] = value;+ }+ if (typeof entry.role === 'string' && entry.role.trim()) out.role = entry.role.trim();+ if (CHARACTER_ARC_TYPES.includes(entry.arcType)) out.arcType = entry.arcType;+ const secrets = Array.isArray(entry.secrets) ? entry.secrets.filter((s) => typeof s === 'string' && s.trim()) : [];+ if (secrets.length) out.secrets = secrets;+ const links = Array.isArray(entry.relationshipLinks) ? entry.relationshipLinks : [];+ if (links.length) {+ out.relationshipLinks = links.map((l) => ({+ targetCharacterId: l?.targetCharacterId || '',+ type: l?.type || 'custom',+ description: l?.description || '',+ }));+ }+ // `name` alone means the writer has authored no framework for this+ // character — the caller drops it rather than prompting against a husk.+ return Object.keys(out).length > 1 ? out : null;+}++// Framework projection for a whole cast, empty entries removed. Returns `[]`+// (not null) when nobody has a framework yet, so a caller can use array+// emptiness as its "omit the section" signal.+export function pickCastFramework(characters) {+ if (!Array.isArray(characters)) return [];+ return characters.map(pickCharacterFramework).filter(Boolean);+}diff --git a/server/lib/index.js b/server/lib/index.jsindex 47d2e6c9d1..79d5b793f0 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -113,6 +113,10 @@ export * from './streamLines.js';export * from './taskDataInputCatalog.js';// The canon field caps storyBible.js sanitizes against, as a pure leaf.export * from './bibleLimits.js';+// The narrative-character framework field list, as a pure leaf — storyBible.js+// re-exports CHARACTER_ARC_TYPES from here, so keep this flat export ahead of+// the namespaced storyBible below.+export * from './characterFramework.js';// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for// back-compat — namespace it so the canonical scenePrompt export wins flat.export * as storyBible from './storyBible.js';diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex da7c06d512..cb2bc388b6 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -17,6 +17,7 @@ import {BIBLE_LIMITS, RELATIONSHIP_LINK_TYPES, RELATIONSHIP_OPPOSITION_AXES,ATTACHMENT_ROLES, VOICE_CANON_SOURCE_POLICIES, IDENTITY_ASSET_ROLES,} from './storyBible.js';+import { CHARACTER_ARC_TYPES, CHARACTER_FRAMEWORK_LIMITS } from './characterFramework.js';import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';import { EFFORT_LEVELS } from './providerModels.js';import { CHECK_SCOPES, CHECK_SEVERITIES } from './editorial/checkInfra/taxonomy.js';@@ -480,8 +481,28 @@ const wrRelationshipLinksField = z.array(z.object({opposition: wrOppositionField.nullable().optional(),locked: z.boolean().optional(),}).strict()).max(BIBLE_LIMITS.RELATIONSHIP_LINKS_PER_CHARACTER_MAX);-export const writersRoomCharacterCreateSchema = z.object({- name: z.string().trim().min(1).max(200),+// Narrative character framework (#6417) — parity with what the Universe cast+// editor already authors and `sanitizeCharacter` already persists. Every field+// is optional AND tolerates its empty value ('' / [] / null) so a writer can+// deliberately clear one; absence leaves the stored value untouched, which is+// the absent-vs-intentionally-empty split the store relies on.+const wrCharFrameworkFields = Object.freeze({+ motivations: z.string().max(CHARACTER_FRAMEWORK_LIMITS.motivations).optional(),+ ghost: z.string().max(CHARACTER_FRAMEWORK_LIMITS.ghost).optional(),+ wound: z.string().max(CHARACTER_FRAMEWORK_LIMITS.wound).optional(),+ lie: z.string().max(CHARACTER_FRAMEWORK_LIMITS.lie).optional(),+ need: z.string().max(CHARACTER_FRAMEWORK_LIMITS.need).optional(),+ want: z.string().max(CHARACTER_FRAMEWORK_LIMITS.want).optional(),+ // '' and null both clear the declared arc; the sanitizer's trimEnum maps+ // anything it doesn't recognize to null rather than rejecting.+ arcType: z.enum(CHARACTER_ARC_TYPES).or(z.literal('')).nullable().optional(),+ secrets: z.array(z.string().trim().min(1).max(BIBLE_LIMITS.SECRET_MAX))+ .max(BIBLE_LIMITS.SECRETS_PER_CHARACTER_MAX).optional(),+});+// Shared between create and update — the two differ only in whether `name` is+// required, and drifting them apart is how `relationshipLinks` ended up+// accepted on one path and dropped on the other.+const wrCharacterFields = Object.freeze({aliases: z.array(z.string().trim().min(1).max(200)).max(20).optional(),role: wrCharTextField.optional(),physicalDescription: wrCharTextField.optional(),@@ -493,20 +514,15 @@ export const writersRoomCharacterCreateSchema = z.object({identityPack: identityPackField.optional(),wardrobes: wrWardrobeField.optional(),relationshipLinks: wrRelationshipLinksField.optional(),+ ...wrCharFrameworkFields,+});+export const writersRoomCharacterCreateSchema = z.object({+ name: z.string().trim().min(1).max(200),+ ...wrCharacterFields,}).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(),- voiceId: wrVoiceIdField.optional(),- voiceCanon: voiceCanonField.optional(),- identityPack: identityPackField.optional(),- wardrobes: wrWardrobeField.optional(),- relationshipLinks: wrRelationshipLinksField.optional(),+ ...wrCharacterFields,}).strict();const wrPlaceTextField = z.string().max(2000);diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 2caa3b371b..dc7027dc3c 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -16,6 +16,7 @@ import { isPlainObject } from './objects.js';import { shortCanonPrimaryField } from './canonPrompt.js';import { trimTo } from './textUtils.js';import { BIBLE_LIMITS } from './bibleLimits.js';+import { CHARACTER_ARC_TYPES } from './characterFramework.js';// Re-export so callers (writers-room domain files) can import a single// canonical normalizer when they need to match places by slugline.@@ -103,11 +104,12 @@ export const PLACE_TIME_OF_DAY = Object.freeze(['dawn', 'day', 'dusk', 'night'])const PLACE_INT_EXT_SET = new Set(PLACE_INT_EXT);const PLACE_TIME_OF_DAY_SET = new Set(PLACE_TIME_OF_DAY);-// Declared character arc type (CWQE Phase 10, #2175). A positive arc overcomes-// the Lie and embraces the Truth; a negative arc is consumed by the Lie; a flat-// arc holds a truth the character already knows and changes the world around-// them instead. Unset (null) keeps the field absent for every pre-#2175 record.-export const CHARACTER_ARC_TYPES = Object.freeze(['positive', 'negative', 'flat']);+// Declared character arc type (CWQE Phase 10, #2175). Defined in the pure+// `characterFramework.js` leaf alongside the rest of the narrative-framework+// field list (so the browser bundle can read it without this module's crypto /+// fileUtils imports) and re-exported here, where every existing caller looks+// for it.+export { CHARACTER_ARC_TYPES };const CHARACTER_ARC_TYPE_SET = new Set(CHARACTER_ARC_TYPES);// Character psychology (#6414). An OPTIONAL layer over the existing framework:diff --git a/server/routes/writersRoom.characterFramework.test.js b/server/routes/writersRoom.characterFramework.test.jsnew file mode 100644index 0000000000..8437c71407--- /dev/null+++ b/server/routes/writersRoom.characterFramework.test.js@@ -0,0 +1,122 @@+/**+ * Route → store round trip for the Writers Room character framework (#6417).+ *+ * Deliberately NOT mocked at the service boundary the way `writersRoom.test.js`+ * is: the regression this catches is the schema and the store disagreeing about+ * which fields exist — a payload the Zod schema accepts and `createBibleStore`+ * then drops on the floor. Only a real request through the real store proves+ * the two halves line up, so `characters.js` / `local.js` run for real against+ * a temp data root and everything else on the router is stubbed out.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import express from 'express';+import { mkdtempSync, rmSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++let tempRoot;++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makePathsProxy(actual, { dataRoot: () => tempRoot });+});++// Everything on the router that would reach a provider, Postgres, or a PTY.+vi.mock('../services/writersRoom/evaluator.js', () => ({+ runAnalysis: vi.fn(),+ listAnalyses: vi.fn(async () => []),+ getAnalysis: vi.fn(),+ persistSceneImage: vi.fn(),+}));+vi.mock('../services/writersRoom/polish.js', () => ({+ startPolish: vi.fn(), attachClient: vi.fn(), cancelPolish: vi.fn(),+ isPolishActive: vi.fn(() => false), listSnapshots: vi.fn(async () => []),+ getSnapshot: vi.fn(), revertToSnapshot: vi.fn(),+}));+vi.mock('../services/writersRoom/syncedReview.js', () => ({ getSyncedReview: vi.fn() }));+vi.mock('../services/writersRoom/liveDirector.js', () => ({+ suggestContinuation: vi.fn(), reserveRenderPreview: vi.fn(),+ suggestCdBridge: vi.fn(), sendToCreativeDirector: vi.fn(),+}));+vi.mock('../services/writersRoom/promoteToPipeline.js', () => ({+ promoteWorkToPipeline: vi.fn(), ERR_NO_DRAFT_BODY: 'WR_PROMOTE_NO_DRAFT_BODY',+}));+vi.mock('../services/catalogExtraction.js', () => ({+ scanProseForIngredientRefs: vi.fn(async () => []),+}));++const { default: writersRoomRouter } = await import('./writersRoom.js');+const { createWork } = await import('../services/writersRoom/local.js');++const app = express();+app.use(express.json());+app.use('/api/writers-room', writersRoomRouter);+app.use(errorMiddleware);++beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-char-framework-'));+});+afterEach(() => {+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });+});++const FRAMEWORK = {+ motivations: 'Keep the crew fed; never be the one who leaves.',+ ghost: 'Left behind at the relay station at nine.',+ wound: 'Reads every silence as abandonment.',+ lie: 'I only matter while I am useful.',+ need: 'Being wanted is not the same as being needed.',+ want: 'Buy back the family salvage license.',+ arcType: 'positive',+ secrets: ['Sold the license years ago'],+};++describe('writers room character routes — narrative framework', () => {+ it('creates, patches, clears and reads back the framework', async () => {+ const work = await createWork({ title: 'Example Work', kind: 'short-story' });+ const base = `/api/writers-room/works/${work.id}/characters`;++ const created = await request(app).post(base).send({ name: 'Wren Calloway', ...FRAMEWORK });+ expect(created.status).toBe(201);+ expect(created.body).toMatchObject(FRAMEWORK);+ const charId = created.body.id;++ const patched = await request(app).patch(`${base}/${charId}`).send({ need: 'Being wanted is enough.' });+ expect(patched.status).toBe(200);+ expect(patched.body.need).toBe('Being wanted is enough.');+ expect(patched.body.ghost).toBe(FRAMEWORK.ghost);++ const cleared = await request(app).patch(`${base}/${charId}`).send({ lie: '', arcType: null, secrets: [] });+ expect(cleared.status).toBe(200);+ expect(cleared.body.lie).toBe('');+ expect(cleared.body.arcType).toBeNull();+ expect(cleared.body.secrets).toEqual([]);++ const listed = await request(app).get(base);+ expect(listed.status).toBe(200);+ expect(listed.body).toHaveLength(1);+ expect(listed.body[0]).toMatchObject({+ want: FRAMEWORK.want, lie: '', arcType: null, secrets: [],+ need: 'Being wanted is enough.',+ });+ });++ it('rejects invalid framework shapes instead of silently coercing them', async () => {+ const work = await createWork({ title: 'Example Work', kind: 'short-story' });+ const base = `/api/writers-room/works/${work.id}/characters`;++ const badArc = await request(app).post(base).send({ name: 'Ines Mbeki', arcType: 'redemption' });+ expect(badArc.status).toBe(400);++ const badSecrets = await request(app).post(base).send({ name: 'Ines Mbeki', secrets: 'a single string' });+ expect(badSecrets.status).toBe(400);++ const unknownField = await request(app).post(base).send({ name: 'Ines Mbeki', theoryOfControl: 'not in this slice' });+ expect(unknownField.status).toBe(400);++ expect((await request(app).get(base)).body).toEqual([]);+ });+});diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.jsindex 3020af2e57..56cb5b2d73 100644--- a/server/services/writersRoom/characters.js+++ b/server/services/writersRoom/characters.js@@ -7,6 +7,7 @@*/import { BIBLE_KIND, normalizeBibleName } from '../../lib/storyBible.js';+import { CHARACTER_FRAMEWORK_FIELDS } from '../../lib/characterFramework.js';import { createBibleStore } from '../bibleStore.js';export const {@@ -21,9 +22,17 @@ export const {idPrefix: 'wr-char-',dedupKey: (entry) => normalizeBibleName(entry?.name),primaryFields: ['name'],+ // Parity with the Universe cast editor (#6417): the writers-room bible+ // shares `sanitizeCharacter`, so the narrative framework already round-trips+ // on disk — it just wasn't reachable through this store. `wardrobes`,+ // `voiceId` and `relationshipLinks` were in the same position: accepted by+ // the route schema, then silently dropped here. Everything the create/update+ // Zod schema accepts must appear in this list or the write is validated and+ // thrown away.editableFields: ['aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes',- 'voiceCanon', 'identityPack',+ 'voiceCanon', 'identityPack', 'wardrobes', 'voiceId',+ ...CHARACTER_FRAMEWORK_FIELDS,],requireOnCreate: (patch) => (String(patch?.name || '').trim() ? null : 'Character name required'),conflictMessage: ({ name }) => `A character named "${name}" already exists`,diff --git a/server/services/writersRoom/characters.test.js b/server/services/writersRoom/characters.test.jsindex a5140bc057..953b001720 100644--- a/server/services/writersRoom/characters.test.js+++ b/server/services/writersRoom/characters.test.js@@ -184,3 +184,86 @@ describe('writers room — characters merge', () => {expect(updated.firstAppearance).toBe('Chapter 1');});});++describe('writers room — character narrative framework (#6417)', () => {+ it('creates, patches and clears the framework the Universe bible already stores', async () => {+ const id = await newWork();+ const created = await createCharacter(id, {+ name: 'Wren Calloway',+ motivations: 'Keep the crew fed; never be the one who leaves.',+ ghost: 'Left behind at the relay station at nine.',+ wound: 'Reads every silence as abandonment.',+ lie: 'I only matter while I am useful.',+ need: 'Being wanted is not the same as being needed.',+ want: 'Buy back the family salvage license.',+ arcType: 'positive',+ secrets: ['Sold the license years ago', 'Cannot read the old charts'],+ });+ expect(created.id).toMatch(/^wr-char-/);+ expect(created.lie).toBe('I only matter while I am useful.');+ expect(created.arcType).toBe('positive');+ expect(created.secrets).toEqual(['Sold the license years ago', 'Cannot read the old charts']);++ // Patch one belief field; every other framework value is untouched.+ const patched = await updateCharacter(id, created.id, {+ need: 'Being wanted is enough.',+ });+ expect(patched.need).toBe('Being wanted is enough.');+ expect(patched.ghost).toBe('Left behind at the relay station at nine.');+ expect(patched.secrets).toHaveLength(2);++ // Present-but-empty is a real clear, not an absent key.+ const cleared = await updateCharacter(id, created.id, {+ lie: '', arcType: null, secrets: [],+ });+ expect(cleared.lie).toBe('');+ expect(cleared.arcType).toBeNull();+ expect(cleared.secrets).toEqual([]);+ expect(cleared.need).toBe('Being wanted is enough.');++ const [reloaded] = await listCharacters(id);+ expect(reloaded.want).toBe('Buy back the family salvage license.');+ expect(reloaded.lie).toBe('');+ expect(reloaded.arcType).toBeNull();+ });++ it('persists the links, wardrobes and voice id the route schema already accepted', async () => {+ // All three were validated by writersRoomCharacter*Schema but missing from+ // the store's editableFields, so the write was accepted and silently+ // dropped — the same class of bug as the framework itself.+ const id = await newWork();+ const other = await createCharacter(id, { name: 'Ines Mbeki' });+ const c = await createCharacter(id, {+ name: 'Wren Calloway',+ relationshipLinks: [{ targetCharacterId: other.id, type: 'rival', description: 'Same salvage claim.' }],+ wardrobes: [{ name: 'Dock coat', description: 'Oil-stained canvas.' }],+ voiceId: 'kokoro:af_heart',+ });+ expect(c.relationshipLinks).toHaveLength(1);+ expect(c.relationshipLinks[0].targetCharacterId).toBe(other.id);+ expect(c.wardrobes[0].name).toBe('Dock coat');+ expect(c.voiceId).toBe('kokoro:af_heart');+ });++ it('extraction never clobbers an authored framework field', async () => {+ const id = await newWork();+ const authored = await createCharacter(id, {+ name: 'Wren Calloway',+ lie: 'AUTHORED — I only matter while I am useful.',+ arcType: 'positive',+ });+ const merged = await mergeExtractedCharacters(id, [{+ name: 'wren calloway',+ lie: 'EXTRACTED — she fears the dark.',+ arcType: 'negative',+ ghost: 'EXTRACTED — left behind at the relay station.',+ secrets: ['Sold the license'],+ }]);+ const refreshed = merged.find((x) => x.id === authored.id);+ expect(refreshed.lie).toBe('AUTHORED — I only matter while I am useful.');+ expect(refreshed.arcType).toBe('positive');+ // Blank fields are still filled from prose — no-clobber, not no-write.+ expect(refreshed.ghost).toBe('EXTRACTED — left behind at the relay station.');+ expect(refreshed.secrets).toEqual(['Sold the license']);+ });+});diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.jsindex c60c140117..4dcc436375 100644--- a/server/services/writersRoom/evaluator.js+++ b/server/services/writersRoom/evaluator.js@@ -17,6 +17,7 @@ import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';import { CUT_TYPES } from '../../lib/editorial/cutApplier.js';import { getWorkWithBody, ensureWorkMediaCollection } from './local.js';import { addItem as addCollectionItem, ERR_DUPLICATE } from '../mediaCollections.js';+import { pickCastFramework } from '../../lib/characterFramework.js';import { listCharacters, mergeExtractedCharacters } from './characters.js';import { listPlaces, mergeExtractedPlaces } from './places.js';import { listObjects, mergeExtractedObjects } from './objects.js';@@ -428,6 +429,18 @@ export async function runAnalysis(workId, { kind } = {}) {}const variables = { work: workCtx, draftBody: body, returnsJson };+ // Author-side review (#6417): hand the editorial pass the cast's AUTHORED+ // framework so it reports delivery against the plan instead of inferring+ // the plan and the delivery from the same prose. Deliberately scoped to+ // `evaluate` — the bible extractors and the script pass are cold reads+ // that must derive everything from the text alone, and `extractBible`+ // already sends existing profiles under its own no-clobber contract. This+ // is a local file read, not an LLM call: nothing here fires until the user+ // asks for an analysis.+ if (kind === 'evaluate') {+ const cast = pickCastFramework(await listCharacters(workId));+ if (cast.length) variables.castFrameworkJson = JSON.stringify(cast, null, 2);+ }const { content, model: usedModel, providerId: usedProvider } = await runStagedLLM(stage, variables, {source: `writers-room-${kind}`,});diff --git a/server/services/writersRoom/evaluator.reviewContext.test.js b/server/services/writersRoom/evaluator.reviewContext.test.jsnew file mode 100644index 0000000000..267d3c56d9--- /dev/null+++ b/server/services/writersRoom/evaluator.reviewContext.test.js@@ -0,0 +1,105 @@+/**+ * The author-side `evaluate` pass must receive the cast's AUTHORED framework+ * (#6417) so it can report delivery against the plan — and nothing may call a+ * provider before the writer explicitly asks for an analysis.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';++let tempRoot;++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return makePathsProxy(actual, { dataRoot: () => tempRoot });+});+vi.mock('../aiProvider.js', () => ({ stripCodeFences: (s) => String(s ?? '') }));+vi.mock('../stageRunner.js', () => ({ runStagedLLM: vi.fn() }));+vi.mock('../bibleExtractor.js', () => ({ extractBible: vi.fn() }));+vi.mock('../sceneExtractor.js', () => ({ extractScenes: vi.fn(), SOURCE_KIND: { PROSE: 'prose' } }));+vi.mock('../mediaCollections.js', () => ({ addItem: vi.fn(), ERR_DUPLICATE: 'DUP' }));++const { runStagedLLM } = await import('../stageRunner.js');+const { runAnalysis, getAnalysis, listAnalyses } = await import('./evaluator.js');+const { createWork, saveDraftBody } = await import('./local.js');+const { createCharacter } = await import('./characters.js');++const EVALUATE_JSON = JSON.stringify({+ logline: 'A salvager buys back what she sold.',+ summary: 'She works the docks.',+ themes: [], strengths: [], issues: [], suggestions: [],+});++beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-review-ctx-'));+ vi.mocked(runStagedLLM).mockReset();+ vi.mocked(runStagedLLM).mockResolvedValue({ content: EVALUATE_JSON, model: 'test-model', providerId: 'test-provider' });+});+afterEach(() => {+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });+});++async function seedWork() {+ const work = await createWork({ title: 'Example Work', kind: 'short-story' });+ await saveDraftBody(work.id, 'The dock lights came on before she did.');+ return work.id;+}++describe('writers room evaluate — review variables', () => {+ it('passes the authored framework to the evaluate stage', async () => {+ const workId = await seedWork();+ await createCharacter(workId, {+ name: 'Wren Calloway',+ role: 'protagonist',+ lie: 'I only matter while I am useful.',+ need: 'Being wanted is not the same as being needed.',+ want: 'Buy back the family salvage license.',+ arcType: 'positive',+ secrets: ['Sold the license years ago'],+ });++ await runAnalysis(workId, { kind: 'evaluate' });++ const [stage, variables] = vi.mocked(runStagedLLM).mock.calls[0];+ expect(stage).toBe('writers-room-evaluate');+ const cast = JSON.parse(variables.castFrameworkJson);+ expect(cast).toHaveLength(1);+ expect(cast[0]).toMatchObject({+ name: 'Wren Calloway',+ role: 'protagonist',+ lie: 'I only matter while I am useful.',+ need: 'Being wanted is not the same as being needed.',+ want: 'Buy back the family salvage license.',+ arcType: 'positive',+ secrets: ['Sold the license years ago'],+ });+ // Render-oriented canon stays out of the editorial prompt.+ expect(cast[0].physicalDescription).toBeUndefined();+ expect(cast[0].imageRefs).toBeUndefined();+ });++ it('omits the variable entirely when no character has an authored framework', async () => {+ const workId = await seedWork();+ await createCharacter(workId, { name: 'Wren Calloway', physicalDescription: 'tall, freckles' });++ await runAnalysis(workId, { kind: 'evaluate' });++ const [, variables] = vi.mocked(runStagedLLM).mock.calls[0];+ expect(variables.castFrameworkJson).toBeUndefined();+ expect(variables.draftBody).toContain('dock lights');+ });++ it('starts no AI work merely from opening the work', async () => {+ const workId = await seedWork();+ await createCharacter(workId, { name: 'Wren Calloway', lie: 'I only matter while I am useful.' });++ // Everything a client does when a writer opens a work: read the work, its+ // bible, and its analysis history.+ await listAnalyses(workId);+ await getAnalysis(workId, 'evaluate').catch(() => null);++ expect(vi.mocked(runStagedLLM)).not.toHaveBeenCalled();+ });+});diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.jsindex 12e17037eb..7a822b66f6 100644--- a/server/services/writersRoom/promoteToPipeline.test.js+++ b/server/services/writersRoom/promoteToPipeline.test.js@@ -107,6 +107,44 @@ describe('promoteWorkToPipeline', () => {expect(universe.objects[0].name).toBe('The Locket');});+ it('retains the authored character framework and valid relationship links (#6417)', async () => {+ const work = await seedWorkWithProse();+ const ines = await createCharacter(work.id, { name: 'Ines Mbeki', role: 'rival' });+ await createCharacter(work.id, {+ name: 'Wren Calloway',+ ghost: 'Left behind at the relay station at nine.',+ wound: 'Reads every silence as abandonment.',+ lie: 'I only matter while I am useful.',+ need: 'Being wanted is not the same as being needed.',+ want: 'Buy back the family salvage license.',+ motivations: 'Keep the crew fed.',+ arcType: 'positive',+ secrets: ['Sold the license years ago'],+ relationshipLinks: [{ targetCharacterId: ines.id, type: 'rival', description: 'Same salvage claim.' }],+ });++ const { series } = await promoteWorkToPipeline(work.id);+ const universe = await universeSvc.getUniverse(series.universeId);+ const wren = universe.characters.find((c) => c.name === 'Wren Calloway');++ expect(wren).toMatchObject({+ ghost: 'Left behind at the relay station at nine.',+ wound: 'Reads every silence as abandonment.',+ lie: 'I only matter while I am useful.',+ need: 'Being wanted is not the same as being needed.',+ want: 'Buy back the family salvage license.',+ motivations: 'Keep the crew fed.',+ arcType: 'positive',+ secrets: ['Sold the license years ago'],+ });+ // Writers-room ids survive the copy, so the link still resolves to a+ // character that exists in the promoted universe.+ expect(wren.id).toMatch(/^wr-char-/);+ expect(wren.relationshipLinks).toHaveLength(1);+ const targetId = wren.relationshipLinks[0].targetCharacterId;+ expect(universe.characters.some((c) => c.id === targetId)).toBe(true);+ });+it('is idempotent: a second promote returns the same series/issue with reused=true', async () => {const work = await seedWorkWithProse();const first = await promoteWorkToPipeline(work.id);