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: author psychology, sliders and relationship links in the Writers Room cast bible (#6417)

[._.]/ Adam Eivy8d31415e91d5
diff --git a/client/src/components/writers-room/BibleSection.jsx b/client/src/components/writers-room/BibleSection.jsx
index 984ef3c529..fa9e4335ff 100644
--- a/client/src/components/writers-room/BibleSection.jsx
+++ b/client/src/components/writers-room/BibleSection.jsx
@@ -26,7 +26,12 @@ import useMounted from '../../hooks/useMounted';
// → 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.
+// can be cleared) | 'custom' (a structured value — a nested object, a
+// numeric axis set, a row list — supplied as
+// `{ seed(item), marshal(value), Component }`. The Component owns its own
+// labels and its own emptiness, so both the shared `<label>` wrapper and
+// the row's "Missing: …" check skip it and no `label` is needed).
+// `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
@@ -113,6 +118,7 @@ export default function BibleSection({ workId, items: itemsProp, onItemsChange,
<BibleEditor
workId={workId}
item={null}
+ items={items}
config={config}
onSaved={(record) => { upsert(record); setCreating(false); }}
onCancel={() => setCreating(false)}
@@ -128,6 +134,7 @@ export default function BibleSection({ workId, items: itemsProp, onItemsChange,
<BibleEditor
workId={workId}
item={item}
+ items={items}
config={config}
onSaved={(updated) => { upsert(updated); setEditingId(null); }}
onDeleted={() => { removeOne(item.id); setEditingId(null); }}
@@ -159,7 +166,7 @@ function BibleRow({ item, config, onEdit, readingTheme }) {
const light = readingTheme === 'light';
const Icon = config.icon;
const blanks = config.fields.filter((f) => {
- if (config.blanksExcludeKeys.includes(f.key)) return false;
+ if (f.kind === 'custom' || config.blanksExcludeKeys.includes(f.key)) return false;
return !String(item[f.key] || '').trim();
});
return (
@@ -209,7 +216,7 @@ function BibleRow({ item, config, onEdit, readingTheme }) {
);
}
-function BibleEditor({ workId, item, config, onSaved, onDeleted, onCancel }) {
+function BibleEditor({ workId, item, items = [], config, onSaved, onDeleted, onCancel }) {
const isCreate = !item;
const { primary, fields } = config;
const [draft, setDraft] = useState(() => {
@@ -217,6 +224,9 @@ function BibleEditor({ workId, item, config, onSaved, onDeleted, onCancel }) {
for (const f of fields) {
if (f.kind === 'csv') seed[f.key] = (item?.[f.key] || []).join(', ');
else if (f.kind === 'lines') seed[f.key] = (item?.[f.key] || []).join('\n');
+ // A structured field seeds from the stored value verbatim (never ''), so
+ // reopening an untouched record and saving round-trips it unchanged.
+ else if (f.kind === 'custom') seed[f.key] = f.seed(item);
else seed[f.key] = item?.[f.key] || '';
}
return seed;
@@ -240,6 +250,7 @@ function BibleEditor({ workId, item, config, onSaved, onDeleted, onCancel }) {
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 if (f.kind === 'custom') payload[f.key] = f.marshal(draft[f.key]);
else payload[f.key] = f.trim ? draft[f.key].trim() : draft[f.key];
}
const result = await (isCreate
@@ -300,19 +311,29 @@ function BibleEditor({ workId, item, config, onSaved, onDeleted, onCancel }) {
{f.heading}
</div>
)}
- <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>
+ {f.kind === 'custom' ? (
+ <f.Component
+ value={draft[f.key]}
+ onChange={(next) => setDraft((d) => ({ ...d, [f.key]: next }))}
+ siblings={items.filter((it) => it.id && it.id !== item?.id)}
+ idPrefix={`bible-field-${f.key}`}
+ inputCls={inputCls}
+ />
+ ) : (
+ <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">
diff --git a/client/src/components/writers-room/BibleSection.test.jsx b/client/src/components/writers-room/BibleSection.test.jsx
index 7de1e5afcf..6b0bdf126a 100644
--- a/client/src/components/writers-room/BibleSection.test.jsx
+++ b/client/src/components/writers-room/BibleSection.test.jsx
@@ -127,6 +127,9 @@ const SCENARIOS = [
createPayload: {
name: 'Bly', aliases: [], role: '', physicalDescription: '', personality: '', background: '', notes: '',
motivations: '', ghost: '', wound: '', lie: '', need: '', want: '', arcType: null, secrets: [],
+ // Structured framework fields ride along as their empty value too — the
+ // server tells a deliberate clear from an untouched key by presence.
+ sliders: {}, psychology: null, relationshipLinks: [],
},
createdRecord: {
id: 'char-2', name: 'Bly', aliases: [], role: '', physicalDescription: '', personality: '',
@@ -139,6 +142,9 @@ const SCENARIOS = [
name: 'Ada', aliases: [], role: 'protagonist', physicalDescription: 'Short, silver hair, sharp eyes.',
personality: '', background: '', notes: '',
motivations: '', ghost: '', wound: '', lie: '', need: '', want: '', arcType: null, secrets: [],
+ // Structured framework fields ride along as their empty value too — the
+ // server tells a deliberate clear from an untouched key by presence.
+ sliders: {}, psychology: null, relationshipLinks: [],
},
},
];
diff --git a/client/src/components/writers-room/CharacterFrameworkEditors.jsx b/client/src/components/writers-room/CharacterFrameworkEditors.jsx
new file mode 100644
index 0000000000..e3e7f65d6e
--- /dev/null
+++ b/client/src/components/writers-room/CharacterFrameworkEditors.jsx
@@ -0,0 +1,284 @@
+/**
+ * Structured character-framework editors for the Writers Room cast bible
+ * (#6417) — the psychology profile (#6414), the Three Sliders (#2175), and the
+ * relationship-link rows (#1287).
+ *
+ * These are `kind: 'custom'` fields on BibleSection's field config: BibleSection
+ * seeds each from the stored record, hands the component a value + `onChange`,
+ * and marshals the result back into the PATCH body. They own their own labels,
+ * so BibleSection skips its shared `<label>` wrapper.
+ *
+ * Every label/placeholder comes from `lib/characterFramework` — the same
+ * descriptors the Universe cast editor renders — so the two surfaces cannot
+ * drift. What stays behind in the Universe editor is the media/voice half
+ * (identity packs, wardrobes, voice design) and the opposing-force tagging on a
+ * link; an existing `opposition` block rides through here untouched.
+ *
+ * Absent vs. intentionally empty: the psychology editor emits the whole object
+ * and lets the server sanitizer collapse an all-blank one to null (a real
+ * clear), rather than re-implementing that rule with a `.length` test.
+ */
+import { Plus, Trash2 } from 'lucide-react';
+import {
+ CHARACTER_PSYCHOLOGY_DRIVE_HINTS,
+ CHARACTER_PSYCHOLOGY_EDITOR_FIELDS,
+ CHARACTER_PSYCHOLOGY_LIMITS,
+ CHARACTER_PSYCHOLOGY_NOTE_FIELD,
+ CHARACTER_SLIDER_AXES,
+ CHARACTER_SLIDER_MAX,
+ CHARACTER_SLIDER_MIN,
+ PSYCHOLOGY_ASSESSMENTS,
+ PSYCHOLOGY_DRIVE_AXES,
+ RELATIONSHIP_LINK_TYPES,
+} from '../../lib/characterFramework';
+import { BIBLE_LIMITS } from '../../lib/bibleLimits';
+
+const asObject = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {});
+const subLabelCls = 'block text-[9px] uppercase tracking-wider text-gray-500';
+const hintCls = 'text-[10px] leading-snug text-gray-500';
+// 44px minimum tap target, per the client mobile convention.
+const addButtonCls = 'inline-flex items-center gap-1 px-1.5 min-h-[44px] text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40';
+const clearButtonCls = 'inline-flex items-center gap-1 px-1.5 min-h-[44px] text-[10px] rounded border border-port-border text-gray-400 hover:text-port-error hover:border-port-error disabled:opacity-40';
+
+// ---------------------------------------------------------------------------
+// Psychology profile (#6414)
+// ---------------------------------------------------------------------------
+
+// The stored profile, verbatim. `null` on a character nobody has assessed —
+// which is the shape the server persists, so an untouched record round-trips.
+export const seedPsychology = (item) => item?.psychology ?? null;
+// The sanitizer already collapses an all-blank profile to null (its "clear"
+// path), so the editor sends what it has and never second-guesses it here.
+export const marshalPsychology = (value) => (value && typeof value === 'object' ? value : null);
+
+export function PsychologyFields({ value, onChange, idPrefix, inputCls }) {
+ const psychology = asObject(value);
+ const drives = asObject(psychology.drives);
+ const commit = (patch) => onChange({ ...psychology, ...patch });
+ const commitDrive = (axis, patch) => commit({
+ drives: { ...drives, [axis]: { ...asObject(drives[axis]), ...patch } },
+ });
+ const explained = psychology.assessment === 'unknown' || psychology.assessment === 'not-applicable';
+ const assessmentId = `${idPrefix}-assessment`;
+ const textareaCls = `${inputCls} font-sans resize-y`;
+ return (
+ <div className="space-y-1.5">
+ <p className={hintCls}>
+ Optional. The Ghost and Wound above stay the origin history; the Want and Need stay the conscious
+ pursuit and the internal alternative. This adds the rule the character operates by and the three
+ drives it manages. Leave it empty and the character stays valid and simply unassessed.
+ </p>
+ <div>
+ <label htmlFor={assessmentId} className={subLabelCls}>Assessment</label>
+ <select
+ id={assessmentId}
+ value={psychology.assessment || ''}
+ onChange={(e) => commit({ assessment: e.target.value || null })}
+ className={inputCls}
+ >
+ <option value="">— unset —</option>
+ {PSYCHOLOGY_ASSESSMENTS.map((a) => <option key={a} value={a}>{a}</option>)}
+ </select>
+ </div>
+ {explained && (
+ <div>
+ <label htmlFor={`${idPrefix}-assessmentNote`} className={subLabelCls}>
+ {CHARACTER_PSYCHOLOGY_NOTE_FIELD.label}
+ </label>
+ <textarea
+ id={`${idPrefix}-assessmentNote`}
+ value={psychology.assessmentNote || ''}
+ onChange={(e) => commit({ assessmentNote: e.target.value })}
+ placeholder={CHARACTER_PSYCHOLOGY_NOTE_FIELD.placeholder}
+ maxLength={CHARACTER_PSYCHOLOGY_NOTE_FIELD.max}
+ rows={2}
+ className={textareaCls}
+ />
+ </div>
+ )}
+ {CHARACTER_PSYCHOLOGY_EDITOR_FIELDS.map((field) => (
+ <div key={field.name}>
+ <label htmlFor={`${idPrefix}-${field.name}`} className={subLabelCls}>{field.label}</label>
+ <textarea
+ id={`${idPrefix}-${field.name}`}
+ value={psychology[field.name] || ''}
+ onChange={(e) => commit({ [field.name]: e.target.value })}
+ placeholder={field.placeholder}
+ maxLength={field.max}
+ rows={2}
+ className={textareaCls}
+ />
+ </div>
+ ))}
+ <p className={hintCls}>
+ Testing pressure and candidate change are what this sheet EXPECTS. What the story actually delivers
+ belongs to the authored character arc, not here.
+ </p>
+ {PSYCHOLOGY_DRIVE_AXES.map((axis) => (
+ <div key={axis} className="space-y-1 border border-port-border/40 rounded p-1.5">
+ <p className="text-[10px] uppercase tracking-wider text-gray-400 capitalize">{axis}</p>
+ <p className={hintCls}>{CHARACTER_PSYCHOLOGY_DRIVE_HINTS[axis]}</p>
+ {['desire', 'fear'].map((leaf) => (
+ <div key={leaf}>
+ <label htmlFor={`${idPrefix}-${axis}-${leaf}`} className={subLabelCls}>{`${axis} ${leaf}`}</label>
+ <input
+ id={`${idPrefix}-${axis}-${leaf}`}
+ value={asObject(drives[axis])[leaf] || ''}
+ onChange={(e) => commitDrive(axis, { [leaf]: e.target.value })}
+ placeholder={leaf === 'desire' ? 'what they reach for on this axis' : 'what they are bracing against on this axis'}
+ maxLength={CHARACTER_PSYCHOLOGY_LIMITS.drive}
+ className={inputCls}
+ />
+ </div>
+ ))}
+ </div>
+ ))}
+ <button
+ type="button"
+ onClick={() => onChange(null)}
+ disabled={!value}
+ className={clearButtonCls}
+ >
+ <Trash2 size={10} /> Clear psychology profile
+ </button>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// The Three Sliders (#2175)
+// ---------------------------------------------------------------------------
+
+// Always an object (the sanitizer keeps all three axes present, null when
+// unrated), so `{}` on a legacy record is the honest seed.
+export const seedSliders = (item) => asObject(item?.sliders);
+export const marshalSliders = (value) => asObject(value);
+
+const SLIDER_VALUES = Array.from(
+ { length: CHARACTER_SLIDER_MAX - CHARACTER_SLIDER_MIN + 1 },
+ (_, i) => CHARACTER_SLIDER_MIN + i,
+);
+
+// A <select> rather than the Universe editor's range input: "unrated" is a real
+// state here and a range slider cannot show it without a second control, which
+// this compact row-level editor has no room for.
+export function SliderFields({ value, onChange, idPrefix, inputCls }) {
+ const sliders = asObject(value);
+ return (
+ <div className="space-y-1.5">
+ <p className={hintCls}>
+ Rule: HIGH (≥7) on at least two, or high on one with room to grow. All-low = boring; all-high = Mary Sue.
+ </p>
+ {CHARACTER_SLIDER_AXES.map((axis) => (
+ <div key={axis}>
+ <label htmlFor={`${idPrefix}-${axis}`} className={`${subLabelCls} capitalize`}>{axis}</label>
+ <select
+ id={`${idPrefix}-${axis}`}
+ value={sliders[axis] == null ? '' : String(sliders[axis])}
+ onChange={(e) => onChange({ ...sliders, [axis]: e.target.value === '' ? null : Number(e.target.value) })}
+ className={inputCls}
+ >
+ <option value="">— unrated —</option>
+ {SLIDER_VALUES.map((n) => <option key={n} value={n}>{n}</option>)}
+ </select>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Relationship links (#1287)
+// ---------------------------------------------------------------------------
+
+export const seedRelationshipLinks = (item) => (Array.isArray(item?.relationshipLinks) ? item.relationshipLinks : []);
+export const marshalRelationshipLinks = (value) => (Array.isArray(value) ? value : []);
+
+export function RelationshipLinkRows({ value, onChange, siblings, idPrefix, inputCls }) {
+ const links = Array.isArray(value) ? value : [];
+ const others = Array.isArray(siblings) ? siblings : [];
+ // Rows are patched, never rebuilt, so an `opposition` block or a `locked`
+ // flag authored in the Universe editor survives a Writers Room edit.
+ const update = (idx, patch) => onChange(links.map((l, i) => (i === idx ? { ...l, ...patch } : l)));
+ return (
+ <div className="space-y-1.5">
+ {links.map((link, idx) => {
+ // A link whose target was deleted points at an id no longer in the
+ // cast. Surface it as an explicit "(missing)" option so the dangling
+ // state is visible and the select still reflects what is stored,
+ // instead of silently snapping to the first cast member.
+ const targetMissing = !!link.targetCharacterId && !others.some((c) => c.id === link.targetCharacterId);
+ return (
+ <div key={link.id || `rel-${idx}`} className="border border-port-border/60 rounded p-1.5 space-y-1">
+ <div className="flex items-end gap-1.5">
+ <div className="flex-1 min-w-0">
+ <label htmlFor={`${idPrefix}-${idx}-target`} className={subLabelCls}>Linked to</label>
+ <select
+ id={`${idPrefix}-${idx}-target`}
+ value={link.targetCharacterId || ''}
+ onChange={(e) => update(idx, { targetCharacterId: e.target.value })}
+ className={inputCls}
+ >
+ {targetMissing && (
+ <option value={link.targetCharacterId}>(missing: {link.targetCharacterId})</option>
+ )}
+ {others.map((c) => <option key={c.id} value={c.id}>{c.name || c.id}</option>)}
+ </select>
+ </div>
+ <div className="w-28 shrink-0">
+ <label htmlFor={`${idPrefix}-${idx}-type`} className={subLabelCls}>Type</label>
+ <select
+ id={`${idPrefix}-${idx}-type`}
+ value={RELATIONSHIP_LINK_TYPES.includes(link.type) ? link.type : 'custom'}
+ onChange={(e) => update(idx, { type: e.target.value })}
+ className={inputCls}
+ >
+ {RELATIONSHIP_LINK_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
+ </select>
+ </div>
+ <button
+ type="button"
+ onClick={() => onChange(links.filter((_, i) => i !== idx))}
+ aria-label={`Remove relationship ${idx + 1}`}
+ title="Remove relationship"
+ className="shrink-0 min-w-[44px] min-h-[44px] flex items-center justify-center text-gray-500 hover:text-port-error"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ <div>
+ <label htmlFor={`${idPrefix}-${idx}-description`} className={subLabelCls}>Description</label>
+ <input
+ id={`${idPrefix}-${idx}-description`}
+ value={link.description || ''}
+ onChange={(e) => update(idx, { description: e.target.value })}
+ placeholder="how they're connected and the tenor of the connection"
+ maxLength={BIBLE_LIMITS.RELATIONSHIP_DESCRIPTION_MAX}
+ className={inputCls}
+ />
+ </div>
+ {link.opposition && (
+ <p className={hintCls}>
+ Tagged as an opposing force on the <span className="text-port-warning">{link.opposition.axis || 'custom'}</span> axis
+ — edit that in the Universe cast editor.
+ </p>
+ )}
+ </div>
+ );
+ })}
+ {others.length === 0 ? (
+ <p className="text-[10px] text-gray-500 italic">
+ Add another character to this work to {links.length ? 're-point these links' : 'link relationships'}.
+ </p>
+ ) : (
+ <button
+ type="button"
+ onClick={() => onChange([...links, { targetCharacterId: others[0].id, type: 'custom', description: '' }])}
+ className={addButtonCls}
+ >
+ <Plus size={10} /> Add relationship
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/writers-room/CharactersBible.framework.test.jsx b/client/src/components/writers-room/CharactersBible.framework.test.jsx
index 0e9fb78ae7..c6b9a5c639 100644
--- a/client/src/components/writers-room/CharactersBible.framework.test.jsx
+++ b/client/src/components/writers-room/CharactersBible.framework.test.jsx
@@ -36,8 +36,11 @@ const CHARACTER = {
want: '',
arcType: null,
secrets: [],
+ sliders: { proactivity: null, likability: null, competence: null },
+ relationshipLinks: [],
source: 'user',
};
+const OTHER = { ...CHARACTER, id: 'wr-char-2', name: 'Ines Mbeki', ghost: '' };
beforeEach(() => { vi.clearAllMocks(); });
afterEach(() => { cleanup(); });
@@ -109,3 +112,95 @@ describe('CharactersBible — narrative framework editing (#6417)', () => {
expect(updateWritersRoomCharacter.mock.calls[1][2]).toMatchObject({ arcType: null, secrets: [] });
});
});
+
+describe('CharactersBible — psychology, sliders and relationship links (#6417)', () => {
+ it('edits the theory of control and a drive, rates an axis, and shows both after a reload', async () => {
+ const BELIEF = 'If I stay useful, nobody leaves.';
+ const FEAR = 'To be set down.';
+ const saved = {
+ ...CHARACTER,
+ psychology: { theoryOfControl: BELIEF, drives: { connection: { fear: FEAR } } },
+ sliders: { proactivity: 8, likability: null, competence: null },
+ };
+ 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(/^Theory of control/), BELIEF);
+ await userEvent.type(screen.getByLabelText('connection fear'), FEAR);
+ await userEvent.selectOptions(screen.getByLabelText('proactivity'), '8');
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());
+ const payload = updateWritersRoomCharacter.mock.calls[0][2];
+ expect(payload.psychology).toMatchObject({
+ theoryOfControl: BELIEF,
+ drives: { connection: { fear: FEAR } },
+ });
+ expect(payload.sliders).toEqual({ proactivity: 8, likability: null, competence: null });
+
+ unmount();
+ listWritersRoomCharacters.mockResolvedValue([saved]);
+ render(<CharactersBible workId="wr-work-1" />);
+ await userEvent.click(await screen.findByRole('button', { name: 'Edit Wren Calloway' }));
+ expect(screen.getByLabelText(/^Theory of control/)).toHaveValue(BELIEF);
+ expect(screen.getByLabelText('connection fear')).toHaveValue(FEAR);
+ expect(screen.getByLabelText('proactivity')).toHaveValue('8');
+ });
+
+ it('clears the whole psychology profile with an explicit null', async () => {
+ const assessed = { ...CHARACTER, psychology: { theoryOfControl: 'Only the work is safe.' } };
+ listWritersRoomCharacters.mockResolvedValue([assessed]);
+ updateWritersRoomCharacter.mockImplementation(async (_w, _id, patch) => ({ ...assessed, ...patch }));
+
+ render(<CharactersBible workId="wr-work-1" />);
+ await screen.findByText('Wren Calloway');
+ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));
+ await userEvent.click(screen.getByRole('button', { name: /Clear psychology profile/ }));
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());
+ expect(updateWritersRoomCharacter.mock.calls[0][2].psychology).toBeNull();
+ });
+
+ it('authors a relationship link against the sibling cast without the Universe picker', async () => {
+ listWritersRoomCharacters.mockResolvedValue([OTHER, 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.click(screen.getByRole('button', { name: /Add relationship/ }));
+ await userEvent.selectOptions(screen.getByLabelText('Type'), 'rival');
+ await userEvent.type(screen.getByLabelText('Description'), 'Same salvage claim.');
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());
+ expect(updateWritersRoomCharacter.mock.calls[0][2].relationshipLinks).toEqual([
+ { targetCharacterId: 'wr-char-2', type: 'rival', description: 'Same salvage claim.' },
+ ]);
+ });
+
+ it('keeps a dangling link visible and removable instead of re-pointing it silently', async () => {
+ const dangling = {
+ ...CHARACTER,
+ relationshipLinks: [{ id: 'rel-1', targetCharacterId: 'wr-char-gone', type: 'rival', description: 'Old claim.' }],
+ };
+ listWritersRoomCharacters.mockResolvedValue([OTHER, dangling]);
+ updateWritersRoomCharacter.mockImplementation(async (_w, _id, patch) => ({ ...dangling, ...patch }));
+
+ render(<CharactersBible workId="wr-work-1" />);
+ await screen.findByText('Wren Calloway');
+ await userEvent.click(screen.getByRole('button', { name: 'Edit Wren Calloway' }));
+ expect(screen.getByLabelText('Linked to')).toHaveValue('wr-char-gone');
+
+ await userEvent.click(screen.getByRole('button', { name: 'Remove relationship 1' }));
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(updateWritersRoomCharacter).toHaveBeenCalled());
+ expect(updateWritersRoomCharacter.mock.calls[0][2].relationshipLinks).toEqual([]);
+ });
+});
diff --git a/client/src/components/writers-room/CharactersBible.jsx b/client/src/components/writers-room/CharactersBible.jsx
index d6aacf981b..117ad673b6 100644
--- a/client/src/components/writers-room/CharactersBible.jsx
+++ b/client/src/components/writers-room/CharactersBible.jsx
@@ -5,6 +5,17 @@ import {
CHARACTER_MOTIVATIONS_FIELD,
CHARACTER_SECRETS_FIELD,
} from '../../lib/characterFramework';
+import {
+ PsychologyFields,
+ RelationshipLinkRows,
+ SliderFields,
+ marshalPsychology,
+ marshalRelationshipLinks,
+ marshalSliders,
+ seedPsychology,
+ seedRelationshipLinks,
+ seedSliders,
+} from './CharacterFrameworkEditors';
import {
listWritersRoomCharacters,
createWritersRoomCharacter,
@@ -32,6 +43,33 @@ const FRAMEWORK_FIELDS = [
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 three structured surfaces, each rendered by its own editor rather than
+ // by BibleSection's flat text/select controls. Same descriptors the Universe
+ // cast editor uses; see CharacterFrameworkEditors.jsx.
+ {
+ key: 'sliders',
+ kind: 'custom',
+ heading: 'Three sliders (proactivity · likability · competence)',
+ seed: seedSliders,
+ marshal: marshalSliders,
+ Component: SliderFields,
+ },
+ {
+ key: 'psychology',
+ kind: 'custom',
+ heading: 'Psychology — theory of control & drives',
+ seed: seedPsychology,
+ marshal: marshalPsychology,
+ Component: PsychologyFields,
+ },
+ {
+ key: 'relationshipLinks',
+ kind: 'custom',
+ heading: 'Relationships',
+ seed: seedRelationshipLinks,
+ marshal: marshalRelationshipLinks,
+ Component: RelationshipLinkRows,
+ },
];
// 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
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 53097f1897..117f83dffd 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -51,7 +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). |
+| `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` / `CHARACTER_PSYCHOLOGY_LIMITS` / `CHARACTER_SLIDER_AXES` / `PSYCHOLOGY_ASSESSMENTS` / `PSYCHOLOGY_DRIVE_AXES` / `RELATIONSHIP_LINK_TYPES` 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`, `CHARACTER_PSYCHOLOGY_EDITOR_FIELDS` / `CHARACTER_PSYCHOLOGY_NOTE_FIELD` / `CHARACTER_PSYCHOLOGY_DRIVE_HINTS` (#6414), and `CHARACTER_SLIDER_MIN` / `CHARACTER_SLIDER_MAX`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |
| `characterIntegrity.js` | Display half of the cast-integrity contract (#6415) — the finding kinds, review statuses and dimension ids mirrored from `server/lib/characterIntegrity.js` (guarded by `characterIntegrity.mirror.test.js`), plus `FINDING_KIND_META` / `REVIEW_STATUS_META` / `DEPTH_META` badge copy, `findingIsRepairable` (which gates the Augment button off `contradictory` findings), `castIntegrityPassed` and `incompleteCoverage`. |
| `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. |
diff --git a/client/src/lib/characterFramework.js b/client/src/lib/characterFramework.js
index 68e995d17f..5f99f50e91 100644
--- a/client/src/lib/characterFramework.js
+++ b/client/src/lib/characterFramework.js
@@ -17,6 +17,11 @@ import {
CHARACTER_FRAMEWORK_FIELDS,
CHARACTER_FRAMEWORK_LIMITS,
CHARACTER_FRAMEWORK_TEXT_FIELDS,
+ CHARACTER_PSYCHOLOGY_LIMITS,
+ CHARACTER_SLIDER_AXES,
+ PSYCHOLOGY_ASSESSMENTS,
+ PSYCHOLOGY_DRIVE_AXES,
+ RELATIONSHIP_LINK_TYPES,
} from '../../../server/lib/characterFramework.js';
import { BIBLE_LIMITS } from './bibleLimits.js';
@@ -25,11 +30,17 @@ export {
CHARACTER_FRAMEWORK_FIELDS,
CHARACTER_FRAMEWORK_LIMITS,
CHARACTER_FRAMEWORK_TEXT_FIELDS,
+ CHARACTER_PSYCHOLOGY_LIMITS,
+ // The Three Sliders axes (#2175) — an unset axis is null, never 0.
+ CHARACTER_SLIDER_AXES,
+ PSYCHOLOGY_ASSESSMENTS,
+ PSYCHOLOGY_DRIVE_AXES,
+ RELATIONSHIP_LINK_TYPES,
};
-// 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']);
+// Slider bounds, so an editor can build its control without restating 1–10.
+export const CHARACTER_SLIDER_MIN = BIBLE_LIMITS.SLIDER_MIN;
+export const CHARACTER_SLIDER_MAX = BIBLE_LIMITS.SLIDER_MAX;
// 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
@@ -61,3 +72,31 @@ export const CHARACTER_SECRETS_FIELD = Object.freeze({
max: BIBLE_LIMITS.SECRET_MAX,
maxItems: BIBLE_LIMITS.SECRETS_PER_CHARACTER_MAX,
});
+
+// Psychology profile editor descriptors (#6414), in authoring order — the same
+// copy both cast editors render. `status` carries its own hint because the
+// label alone reads as wealth or dominance, which it is not.
+export const CHARACTER_PSYCHOLOGY_EDITOR_FIELDS = Object.freeze([
+ { name: 'theoryOfControl', label: 'Theory of control (one sentence)', placeholder: 'the rule they operate by — "if I stay useful, nobody leaves"', max: CHARACTER_PSYCHOLOGY_LIMITS.theoryOfControl },
+ { name: 'strategy', label: 'Strategy it motivates', placeholder: "the behavior the theory produces — \"takes on everyone else's work, never asks for anything\"", max: CHARACTER_PSYCHOLOGY_LIMITS.strategy },
+ { name: 'protectiveBenefit', label: 'What it protects', placeholder: 'the real thing it keeps them from feeling or losing', max: CHARACTER_PSYCHOLOGY_LIMITS.protectiveBenefit },
+ { name: 'presentCost', label: 'What it costs now', placeholder: 'the price the strategy charges in the present', max: CHARACTER_PSYCHOLOGY_LIMITS.presentCost },
+ { name: 'testingPressure', label: 'Anticipated testing pressure', placeholder: 'what would put the theory under load — anticipated, not yet dramatized', max: CHARACTER_PSYCHOLOGY_LIMITS.testingPressure },
+ { name: 'candidateChange', label: 'Candidate change', placeholder: 'the revision the theory might undergo if the pressure lands', max: CHARACTER_PSYCHOLOGY_LIMITS.candidateChange },
+]);
+
+// The escape-hatch explanation shown only for a non-`assessed` assessment: a
+// hive, a weather front, or a deliberately opaque character is a legitimate
+// answer, said out loud rather than by leaving the form blank.
+export const CHARACTER_PSYCHOLOGY_NOTE_FIELD = Object.freeze({
+ name: 'assessmentNote',
+ label: 'Why',
+ placeholder: 'why this character has no legible theory of control, or how to read one for a nonhuman',
+ max: CHARACTER_PSYCHOLOGY_LIMITS.assessmentNote,
+});
+
+export const CHARACTER_PSYCHOLOGY_DRIVE_HINTS = Object.freeze({
+ survival: 'staying safe, fed, intact — physical or existential continuity',
+ connection: 'being known, kept, belonged to',
+ status: 'perceived value to a group — respect, standing, being counted; NOT wealth or dominance',
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 7fb87e6457..e188907eba 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -110,7 +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). |
+| `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, the psychology profile and the Three Sliders), `CHARACTER_FRAMEWORK_LIMITS`, the psychology/slider/link vocabularies re-exported by `storyBible.js` (`PSYCHOLOGY_DRIVE_AXES`, `PSYCHOLOGY_ASSESSMENTS`, `CHARACTER_PSYCHOLOGY_TEXT_FIELDS`, `CHARACTER_PSYCHOLOGY_LIMITS`, `CHARACTER_SLIDER_AXES`, `RELATIONSHIP_LINK_TYPES`), 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). |
| `characterIntegrity.js` | The shared cast-integrity contract (#6415): `INTEGRITY_FINDING_KINDS` (`missing` / `underspecified` / `contradictory`), the five `INTEGRITY_DIMENSIONS`, `CHARACTER_REVIEW_STATUSES` (`passed` vs `not-reviewed` / `truncated` / `stale` — incomplete coverage can never read as clean), `characterIntegrityDepth` (minor roles / flat arcs / an explained `unknown` psychology get lighter requirements), the no-provider `characterCompletenessFindings` / `buildCastIntegrityReport`, the validating `mergeSemanticFindings`, and `characterFingerprint` / `staleReportCharacterIds` (reports are derived, never persisted — the fingerprint is what makes a stale one detectable). |
| `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. |
diff --git a/server/lib/characterFramework.js b/server/lib/characterFramework.js
index 92ddb913a6..ca4e84c5b0 100644
--- a/server/lib/characterFramework.js
+++ b/server/lib/characterFramework.js
@@ -47,10 +47,13 @@ export const CHARACTER_FRAMEWORK_LIMITS = Object.freeze({
// 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.
+// link list (#1287); `arcType` is one of CHARACTER_ARC_TYPES or null;
+// `psychology` is the optional theory-of-control + drives profile (#6414),
+// absent until assessed; `sliders` is the always-present Three-Sliders object
+// (#2175) whose axes are null until rated.
export const CHARACTER_FRAMEWORK_FIELDS = Object.freeze([
...CHARACTER_FRAMEWORK_TEXT_FIELDS,
- 'arcType', 'secrets', 'relationshipLinks',
+ 'arcType', 'secrets', 'relationshipLinks', 'psychology', 'sliders',
]);
// Projection used to hand an author-side review the framework it is supposed
@@ -89,3 +92,49 @@ export function pickCastFramework(characters) {
if (!Array.isArray(characters)) return [];
return characters.map(pickCharacterFramework).filter(Boolean);
}
+
+// Optional structured psychology profile (#6414) — the character's operating
+// rule and the three drives it manages. Defined here, beside the rest of the
+// framework, so the Zod schemas, the Universe cast editor and the Writers Room
+// bible read one list instead of hand-mirroring the axes in each. `status`
+// means PERCEIVED VALUE TO A GROUP — not wealth, not dominance — which is why
+// the axis carries its own editor hint rather than relying on the label.
+export const PSYCHOLOGY_DRIVE_AXES = Object.freeze(['survival', 'connection', 'status']);
+
+// An author may rule the profile out rather than leave it blank: `unknown` and
+// `not-applicable` both expect an explanation in `assessmentNote`, which is
+// what makes the entry read as ASSESSED instead of unfilled.
+export const PSYCHOLOGY_ASSESSMENTS = Object.freeze(['assessed', 'unknown', 'not-applicable']);
+
+// The prose half of the profile, in authoring order. `assessmentNote` is NOT
+// here: it is the escape-hatch explanation, shown only for a non-`assessed`
+// assessment, and it is capped separately below.
+export const CHARACTER_PSYCHOLOGY_TEXT_FIELDS = Object.freeze([
+ 'theoryOfControl', 'strategy', 'protectiveBenefit', 'presentCost',
+ 'testingPressure', 'candidateChange',
+]);
+
+// Per-field caps for the profile. `assessmentNote` and `drive` (shared by every
+// drive `desire` / `fear` leaf) sit alongside the prose fields so a schema or an
+// editor can size every input from one map.
+export const CHARACTER_PSYCHOLOGY_LIMITS = Object.freeze({
+ theoryOfControl: BIBLE_LIMITS.THEORY_OF_CONTROL_MAX,
+ strategy: BIBLE_LIMITS.PSYCHOLOGY_STRATEGY_MAX,
+ protectiveBenefit: BIBLE_LIMITS.PSYCHOLOGY_PROTECTION_MAX,
+ presentCost: BIBLE_LIMITS.PSYCHOLOGY_COST_MAX,
+ testingPressure: BIBLE_LIMITS.PSYCHOLOGY_PRESSURE_MAX,
+ candidateChange: BIBLE_LIMITS.PSYCHOLOGY_CHANGE_MAX,
+ assessmentNote: BIBLE_LIMITS.PSYCHOLOGY_NOTE_MAX,
+ drive: BIBLE_LIMITS.PSYCHOLOGY_DRIVE_FIELD_MAX,
+});
+
+// The Three Sliders (#2175) — integers in [SLIDER_MIN, SLIDER_MAX], each null
+// when the axis was never rated (distinct from a deliberate low rating).
+export const CHARACTER_SLIDER_AXES = Object.freeze(['proactivity', 'likability', 'competence']);
+
+// Structured relationship-link archetypes (#1287). An unrecognized value
+// (legacy record, newer peer) coerces to `custom` in the sanitizer rather than
+// dropping the link, so this list bounds the EDITOR's choices, not the wire.
+export const RELATIONSHIP_LINK_TYPES = Object.freeze([
+ 'ally', 'antagonist', 'rival', 'mentor', 'love-interest', 'family', 'custom',
+]);
diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.js
index cb2bc388b6..de2c3499d4 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -17,7 +17,15 @@ 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 {
+ CHARACTER_ARC_TYPES,
+ CHARACTER_FRAMEWORK_LIMITS,
+ CHARACTER_PSYCHOLOGY_LIMITS,
+ CHARACTER_PSYCHOLOGY_TEXT_FIELDS,
+ CHARACTER_SLIDER_AXES,
+ PSYCHOLOGY_ASSESSMENTS,
+ PSYCHOLOGY_DRIVE_AXES,
+} 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';
@@ -481,6 +489,31 @@ const wrRelationshipLinksField = z.array(z.object({
opposition: wrOppositionField.nullable().optional(),
locked: z.boolean().optional(),
}).strict()).max(BIBLE_LIMITS.RELATIONSHIP_LINKS_PER_CHARACTER_MAX);
+// Optional psychology profile (#6414) and the Three Sliders (#2175) — the two
+// structured surfaces the Universe cast editor already authors. Both are
+// clearable: `psychology: null` (or an all-blank object) drops the profile so a
+// character reads as unassessed again rather than keeping an empty husk, and a
+// slider axis set to null un-rates it without disturbing the other two.
+const wrPsychologyDriveField = z.object({
+ desire: z.string().max(CHARACTER_PSYCHOLOGY_LIMITS.drive).nullable().optional(),
+ fear: z.string().max(CHARACTER_PSYCHOLOGY_LIMITS.drive).nullable().optional(),
+}).strict();
+const wrPsychologyField = z.object({
+ ...Object.fromEntries(CHARACTER_PSYCHOLOGY_TEXT_FIELDS.map((field) => [
+ field, z.string().max(CHARACTER_PSYCHOLOGY_LIMITS[field]).nullable().optional(),
+ ])),
+ // '' and null both unset the assessment; the sanitizer's trimEnum maps an
+ // unrecognized token to null rather than rejecting it.
+ assessment: z.enum(PSYCHOLOGY_ASSESSMENTS).or(z.literal('')).nullable().optional(),
+ assessmentNote: z.string().max(CHARACTER_PSYCHOLOGY_LIMITS.assessmentNote).nullable().optional(),
+ drives: z.object(Object.fromEntries(
+ PSYCHOLOGY_DRIVE_AXES.map((axis) => [axis, wrPsychologyDriveField.nullable().optional()]),
+ )).strict().nullable().optional(),
+}).strict();
+const wrSlidersField = z.object(Object.fromEntries(CHARACTER_SLIDER_AXES.map((axis) => [
+ axis,
+ z.number().int().min(BIBLE_LIMITS.SLIDER_MIN).max(BIBLE_LIMITS.SLIDER_MAX).nullable().optional(),
+]))).strict();
// 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
@@ -498,6 +531,8 @@ const wrCharFrameworkFields = Object.freeze({
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(),
+ psychology: wrPsychologyField.nullable().optional(),
+ sliders: wrSlidersField.nullable().optional(),
});
// Shared between create and update — the two differ only in whether `name` is
// required, and drifting them apart is how `relationshipLinks` ended up
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index dc7027dc3c..294c0e625b 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -16,7 +16,13 @@ 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';
+import {
+ CHARACTER_ARC_TYPES,
+ CHARACTER_SLIDER_AXES,
+ PSYCHOLOGY_ASSESSMENTS,
+ PSYCHOLOGY_DRIVE_AXES,
+ RELATIONSHIP_LINK_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.
@@ -71,15 +77,14 @@ export const BIBLE_KIND = Object.freeze({
});
// Structured relationship-link taxonomy (#1287). `type` is the dynamic
-// between two characters; `custom` lets the writer name one the list misses
-// (the free-text `description` carries the specifics). `opposition.axis`
-// tags a binary-force tension (hunter/prey, winner/loser…) the reader tracks
-// to see whether the roles ever reverse. Both default to `custom` on an
-// unrecognized value rather than dropping the link, so a legacy/peer payload
-// with a future type still round-trips (its prose description is preserved).
-export const RELATIONSHIP_LINK_TYPES = Object.freeze([
- 'ally', 'antagonist', 'rival', 'mentor', 'love-interest', 'family', 'custom',
-]);
+// between two characters and lives in the pure `characterFramework.js` leaf so
+// the browser bundle can render the picker; re-exported here for the existing
+// server-side callers. `opposition.axis` tags a binary-force tension
+// (hunter/prey, winner/loser…) the reader tracks to see whether the roles ever
+// reverse. Both default to `custom` on an unrecognized value rather than
+// dropping the link, so a legacy/peer payload with a future type still
+// round-trips (its prose description is preserved).
+export { RELATIONSHIP_LINK_TYPES };
export const RELATIONSHIP_OPPOSITION_AXES = Object.freeze([
'winner/loser', 'smart/dumb', 'hunter/prey', 'predator/prey', 'custom',
]);
@@ -121,14 +126,10 @@ const CHARACTER_ARC_TYPE_SET = new Set(CHARACTER_ARC_TYPES);
// rather than be its literal opposite.
//
// The three drives are the pressures the theory is built to manage. `status`
-// means PERCEIVED VALUE TO A GROUP — not wealth, not dominance.
-export const PSYCHOLOGY_DRIVE_AXES = Object.freeze(['survival', 'connection', 'status']);
-// An author may rule the profile out rather than leave it blank: `unknown`
-// (not yet decided / deliberately opaque) and `not-applicable` (a hive, a
-// weather system, an unpersoned intelligence) both expect an explanation in
-// `assessmentNote`, which is what makes the entry read as ASSESSED instead of
-// unfilled. `assessed` is the ordinary authored case.
-export const PSYCHOLOGY_ASSESSMENTS = Object.freeze(['assessed', 'unknown', 'not-applicable']);
+// means PERCEIVED VALUE TO A GROUP — not wealth, not dominance. Both lists live
+// in the pure `characterFramework.js` leaf (the cast editors need them in the
+// browser bundle) and are re-exported here for every existing server caller.
+export { PSYCHOLOGY_DRIVE_AXES, PSYCHOLOGY_ASSESSMENTS };
const PSYCHOLOGY_ASSESSMENT_SET = new Set(PSYCHOLOGY_ASSESSMENTS);
const trimEnum = (raw, allowed) => {
@@ -914,11 +915,7 @@ function ensureSlider(raw) {
// round-trip never strips it — mirrors the reveal-gating always-present pattern.
function sanitizeCharacterSliders(raw) {
const src = raw && typeof raw === 'object' ? raw : {};
- return {
- proactivity: ensureSlider(src.proactivity),
- likability: ensureSlider(src.likability),
- competence: ensureSlider(src.competence),
- };
+ return Object.fromEntries(CHARACTER_SLIDER_AXES.map((axis) => [axis, ensureSlider(src[axis])]));
}
// Shared canon extras applied to every kind. Persists explicit `locked: true`
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 8230feaad5..14e246d83c 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -1963,6 +1963,39 @@ describe('validation.js', () => {
});
});
+ describe('writersRoomCharacterUpdateSchema — psychology & sliders (#6417)', () => {
+ it('accepts a partial psychology profile, an explicit clear, and a rated axis', () => {
+ expect(writersRoomCharacterUpdateSchema.safeParse({
+ psychology: {
+ theoryOfControl: 'If I stay useful, nobody leaves.',
+ assessment: 'assessed',
+ drives: { connection: { desire: 'To be kept' } },
+ },
+ sliders: { proactivity: 8 },
+ }).success).toBe(true);
+ // Present-but-empty is the clear path the store relies on.
+ expect(writersRoomCharacterUpdateSchema.safeParse({
+ psychology: null,
+ sliders: { proactivity: null, likability: null, competence: null },
+ }).success).toBe(true);
+ });
+
+ it('rejects an unknown drive axis, an out-of-range slider, and a stray key', () => {
+ expect(writersRoomCharacterUpdateSchema.safeParse({
+ psychology: { drives: { ambition: { desire: 'more' } } },
+ }).success).toBe(false);
+ expect(writersRoomCharacterUpdateSchema.safeParse({
+ sliders: { proactivity: 11 },
+ }).success).toBe(false);
+ expect(writersRoomCharacterUpdateSchema.safeParse({
+ sliders: { proactivity: 4.5 },
+ }).success).toBe(false);
+ expect(writersRoomCharacterUpdateSchema.safeParse({
+ psychology: { theoryOfControl: 'ok', freudianSlip: 'nope' },
+ }).success).toBe(false);
+ });
+ });
+
describe('writersRoomObjectUpdateSchema — attachments (#1288)', () => {
it('accepts a well-formed attachment', () => {
const result = writersRoomObjectUpdateSchema.safeParse({
diff --git a/server/services/writersRoom/characters.test.js b/server/services/writersRoom/characters.test.js
index 953b001720..a725ba9172 100644
--- a/server/services/writersRoom/characters.test.js
+++ b/server/services/writersRoom/characters.test.js
@@ -267,3 +267,90 @@ describe('writers room — character narrative framework (#6417)', () => {
expect(refreshed.secrets).toEqual(['Sold the license']);
});
});
+
+describe('writers room — psychology, sliders and links (#6417)', () => {
+ it('creates, patches and clears the psychology profile and the Three Sliders', async () => {
+ const id = await newWork();
+ const created = await createCharacter(id, {
+ name: 'Wren Calloway',
+ psychology: {
+ theoryOfControl: 'If I stay useful, nobody leaves.',
+ strategy: 'Takes on everyone else’s work and never asks for anything.',
+ drives: { connection: { desire: 'To be kept', fear: 'To be set down' } },
+ },
+ sliders: { proactivity: 8, competence: 6 },
+ });
+ expect(created.psychology.theoryOfControl).toBe('If I stay useful, nobody leaves.');
+ expect(created.psychology.drives.connection.fear).toBe('To be set down');
+ // Unfilled axes materialize as blank leaves, never as an absent slot.
+ expect(created.psychology.drives.survival).toEqual({ desire: '', fear: '' });
+ expect(created.sliders).toEqual({ proactivity: 8, likability: null, competence: 6 });
+
+ // Patch one leaf; the rest of the profile and the sliders are untouched.
+ const patched = await updateCharacter(id, created.id, {
+ psychology: { ...created.psychology, presentCost: 'Never says what she wants.' },
+ });
+ expect(patched.psychology.presentCost).toBe('Never says what she wants.');
+ expect(patched.psychology.theoryOfControl).toBe('If I stay useful, nobody leaves.');
+ expect(patched.sliders.proactivity).toBe(8);
+
+ // An assessment alone keeps the profile: the author ruled the interior out
+ // rather than leaving it unfilled, and that is a real answer.
+ const ruledOut = await updateCharacter(id, created.id, {
+ psychology: { assessment: 'not-applicable', assessmentNote: 'A weather front, not a person.' },
+ });
+ expect(ruledOut.psychology.assessment).toBe('not-applicable');
+ expect(ruledOut.psychology.theoryOfControl).toBe('');
+
+ // Present-but-empty is a real clear; an absent key would have preserved it.
+ const cleared = await updateCharacter(id, created.id, {
+ psychology: null,
+ sliders: { proactivity: null, likability: null, competence: null },
+ });
+ expect(cleared.psychology).toBeUndefined();
+ expect(cleared.sliders).toEqual({ proactivity: null, likability: null, competence: null });
+
+ const [reloaded] = await listCharacters(id);
+ expect(reloaded.psychology).toBeUndefined();
+ expect(reloaded.sliders.proactivity).toBeNull();
+ });
+
+ it('keeps an authored psychology profile when extraction proposes another', async () => {
+ const id = await newWork();
+ const authored = await createCharacter(id, {
+ name: 'Wren Calloway',
+ psychology: { theoryOfControl: 'AUTHORED — if I stay useful, nobody leaves.' },
+ });
+ const merged = await mergeExtractedCharacters(id, [{
+ name: 'wren calloway',
+ psychology: { theoryOfControl: 'EXTRACTED — she fears the dark.' },
+ }]);
+ const refreshed = merged.find((x) => x.id === authored.id);
+ expect(refreshed.psychology.theoryOfControl).toBe('AUTHORED — if I stay useful, nobody leaves.');
+ });
+
+ it('patches a relationship link without dropping its opposing-force tag', async () => {
+ // The Writers Room row editor authors target/type/description only; an
+ // `opposition` block tagged in the Universe cast editor rides through.
+ 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.',
+ opposition: { axis: 'winner/loser', thisRole: 'challenger', targetRole: 'holder' },
+ }],
+ });
+ const link = c.relationshipLinks[0];
+ const patched = await updateCharacter(id, c.id, {
+ relationshipLinks: [{ ...link, type: 'antagonist', description: 'Same claim, now in court.' }],
+ });
+ expect(patched.relationshipLinks[0].type).toBe('antagonist');
+ expect(patched.relationshipLinks[0].opposition.axis).toBe('winner/loser');
+
+ const emptied = await updateCharacter(id, c.id, { relationshipLinks: [] });
+ expect(emptied.relationshipLinks).toEqual([]);
+ });
+});
diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.js
index 7a822b66f6..05f7190f9d 100644
--- a/server/services/writersRoom/promoteToPipeline.test.js
+++ b/server/services/writersRoom/promoteToPipeline.test.js
@@ -120,6 +120,12 @@ describe('promoteWorkToPipeline', () => {
motivations: 'Keep the crew fed.',
arcType: 'positive',
secrets: ['Sold the license years ago'],
+ psychology: {
+ theoryOfControl: 'If I stay useful, nobody leaves.',
+ assessment: 'assessed',
+ drives: { connection: { desire: 'To be kept', fear: 'To be set down' } },
+ },
+ sliders: { proactivity: 8, competence: 6 },
relationshipLinks: [{ targetCharacterId: ines.id, type: 'rival', description: 'Same salvage claim.' }],
});
@@ -137,6 +143,9 @@ describe('promoteWorkToPipeline', () => {
arcType: 'positive',
secrets: ['Sold the license years ago'],
});
+ expect(wren.psychology.theoryOfControl).toBe('If I stay useful, nobody leaves.');
+ expect(wren.psychology.drives.connection.fear).toBe('To be set down');
+ expect(wren.sliders).toEqual({ proactivity: 8, likability: null, competence: 6 });
// 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-/);