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: model character theory of control and survival/connection/status drives (#6414)
[._.]/ Adam Eivybf496f0e816d
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsxindex 8e0a2b89a7..06c88fc8d0 100644--- a/client/src/components/universe/CharacterDetailEditor.jsx+++ b/client/src/components/universe/CharacterDetailEditor.jsx@@ -14,7 +14,7 @@ import { useEffect, useRef, useState } from 'react';import {Plus, Trash2, WandSparkles, Loader2,Palette, Hand, Smile, Package, BookOpen, Eye, Activity, Users, Swords,- Drama, KeyRound, Mic, Images, BadgeCheck, Play,+ Drama, KeyRound, Mic, Images, BadgeCheck, Play, Compass,} from 'lucide-react';import { BIBLE_LIMITS as L } from '../../lib/bibleLimits';import useFieldDraft from '../../hooks/useFieldDraft';@@ -63,8 +63,8 @@ const SECTIONS = Object.freeze([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 (false belief)', placeholder: 'state in one sentence — "I only matter if I win"', max: L.LIE_MAX, type: 'textarea' },- { name: 'need', label: 'Need (Truth — opposite of the Lie)', placeholder: 'the direct opposite of the Lie — "I matter whether I win or lose"', max: L.NEED_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' },],},@@ -1167,6 +1167,201 @@ function VoiceProfileSection({ universeId, entry, disabled }) {);}+// Mirrors `PSYCHOLOGY_DRIVE_AXES` / `PSYCHOLOGY_ASSESSMENTS` in+// server/lib/storyBible.js (#6414). `status` is PERCEIVED VALUE TO A GROUP —+// not wealth, not dominance — which is why the axis carries its own hint below+// rather than relying on the label alone.+const PSYCHOLOGY_DRIVE_AXES = Object.freeze(['survival', 'connection', 'status']);+const PSYCHOLOGY_ASSESSMENTS = Object.freeze(['assessed', 'unknown', 'not-applicable']);+const 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',+});+const PSYCHOLOGY_PROSE_FIELDS = Object.freeze([+ {+ name: 'theoryOfControl',+ label: 'Theory of control (one sentence)',+ placeholder: 'the rule they operate by — "if I stay useful, nobody leaves"',+ max: L.THEORY_OF_CONTROL_MAX,+ },+ {+ name: 'strategy',+ label: 'Strategy it motivates',+ placeholder: 'the behavior the theory produces — "takes on everyone else\'s work, never asks for anything"',+ max: L.PSYCHOLOGY_STRATEGY_MAX,+ },+ {+ name: 'protectiveBenefit',+ label: 'What it protects',+ placeholder: 'the real thing it keeps them from feeling or losing',+ max: L.PSYCHOLOGY_PROTECTION_MAX,+ },+ {+ name: 'presentCost',+ label: 'What it costs now',+ placeholder: 'the price the strategy charges in the present',+ max: L.PSYCHOLOGY_COST_MAX,+ },+ {+ name: 'testingPressure',+ label: 'Anticipated testing pressure',+ placeholder: 'what would put the theory under load — anticipated, not yet dramatized',+ max: L.PSYCHOLOGY_PRESSURE_MAX,+ },+ {+ name: 'candidateChange',+ label: 'Candidate change',+ placeholder: 'the revision the theory might undergo if the pressure lands',+ max: L.PSYCHOLOGY_CHANGE_MAX,+ },+]);++// One draft-buffered textarea inside the psychology profile. A sub-component+// because `useFieldDraft` is a hook and cannot be called inside a `.map`.+function PsychologyField({ id, label, hint, placeholder, max, value, onCommit, disabled, rows = 2 }) {+ const draft = useFieldDraft(value || '', onCommit);+ return (+ <div className="space-y-0.5">+ <label htmlFor={id} className="block text-[10px] uppercase tracking-wider text-gray-500">{label}</label>+ {hint ? <p className="text-[10px] leading-snug text-gray-500">{hint}</p> : null}+ <textarea+ id={id} value={draft.value} onChange={draft.onChange} onBlur={draft.onBlur}+ placeholder={placeholder} maxLength={max} disabled={disabled} rows={rows}+ className={REL_INPUT_CLASS}+ />+ </div>+ );+}++/**+ * Optional structured psychology (#6414) — the character's operating rule and+ * the survival / connection / status drives it serves.+ *+ * Deliberately NOT auto-derived from the Lie. The Lie is an optional judgment+ * ABOUT a belief; the theory of control is the belief stated as the rule the+ * character actually runs on. They are usually related and are never the same+ * statement, so an existing Lie is offered as read-only legacy context and a+ * suggested starting point — never copied in, never asserted equivalent.+ * Absent on every character nobody has assessed, which is why the summary says+ * "unassessed" rather than showing an empty form as if it were filled in.+ */+function PsychologySection({ entry, onPatch, disabled }) {+ const psychology = (entry.psychology && typeof entry.psychology === 'object') ? entry.psychology : {};+ const drives = (psychology.drives && typeof psychology.drives === 'object') ? psychology.drives : {};+ const commit = (patch) => onPatch?.({ psychology: { ...psychology, ...patch } });+ const commitDrive = (axis, patch) => commit({+ drives: { ...drives, [axis]: { ...(drives[axis] || {}), ...patch } },+ });+ const filled = PSYCHOLOGY_PROSE_FIELDS.filter((f) => String(psychology[f.name] || '').trim()).length+ + PSYCHOLOGY_DRIVE_AXES.filter((axis) => String(drives[axis]?.desire || '').trim() || String(drives[axis]?.fear || '').trim()).length;+ // "unassessed" is keyed on the PERSISTED object, not on the filled count: an+ // author who ruled the profile out wrote a real assessment even though every+ // prose leaf is blank, and the clear action has to stay reachable for them.+ const hasProfile = Boolean(entry.psychology);+ const summary = !hasProfile+ ? 'unassessed'+ : psychology.assessment && psychology.assessment !== 'assessed'+ ? psychology.assessment+ : `${filled}/${PSYCHOLOGY_PROSE_FIELDS.length + PSYCHOLOGY_DRIVE_AXES.length} filled`;+ const assessmentId = `chr-psych-assessment-${entry.id}`;+ return (+ <BoxedSection icon={Compass} label="Psychology (theory of control & drives)" summary={summary}>+ <p className="text-[10px] leading-snug text-gray-500">+ Optional. The Ghost and Wound above stay the origin history; the Want and Need stay the conscious+ pursuit and the internal alternative. This section 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>+ {entry.lie ? (+ <p className="text-[10px] leading-snug text-gray-400 border-l-2 border-port-border pl-2">+ <span className="uppercase tracking-wider text-gray-500">Legacy context — the Lie you already wrote:</span>{' '}+ <span className="italic">{entry.lie}</span>{' '}+ A suggested starting point only. The Lie is a judgment about a belief; the theory of control states+ the belief as the character's operating rule. They are not the same sentence, and the Need may+ qualify the belief rather than be its literal opposite.+ </p>+ ) : null}+ <div className="space-y-0.5">+ <label htmlFor={assessmentId} className="block text-[10px] uppercase tracking-wider text-gray-500">+ Assessment+ </label>+ <select+ id={assessmentId} value={psychology.assessment || ''} disabled={disabled}+ onChange={(e) => commit({ assessment: e.target.value || null })}+ className={REL_INPUT_CLASS}+ >+ <option value="">— unset —</option>+ {PSYCHOLOGY_ASSESSMENTS.map((a) => <option key={a} value={a}>{a}</option>)}+ </select>+ </div>+ {psychology.assessment === 'unknown' || psychology.assessment === 'not-applicable' ? (+ <PsychologyField+ id={`chr-psych-note-${entry.id}`}+ label="Why"+ hint="Required for unknown / not-applicable. A hive, a weather front, or an intelligence with no interior is a legitimate answer — say so here rather than inventing a human interior."+ placeholder="why this character has no legible theory of control, or how to read one for a nonhuman"+ max={L.PSYCHOLOGY_NOTE_MAX}+ value={psychology.assessmentNote}+ onCommit={(v) => commit({ assessmentNote: v })}+ disabled={disabled}+ />+ ) : null}+ {PSYCHOLOGY_PROSE_FIELDS.map((field) => (+ <PsychologyField+ key={field.name}+ id={`chr-psych-${entry.id}-${field.name}`}+ label={field.label}+ placeholder={field.placeholder}+ max={field.max}+ value={psychology[field.name]}+ onCommit={(v) => commit({ [field.name]: v })}+ disabled={disabled}+ />+ ))}+ <p className="text-[10px] leading-snug text-gray-500">+ Testing pressure and candidate change are what this character sheet EXPECTS. What the story actually+ delivers belongs to the authored character arc on the series, not here.+ </p>+ <div className="space-y-2">+ <span className="block text-[10px] uppercase tracking-wider text-gray-500">Drives</span>+ {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="text-[10px] leading-snug text-gray-500">{DRIVE_HINTS[axis]}</p>+ <PsychologyField+ id={`chr-psych-${entry.id}-${axis}-desire`}+ label={`${axis} desire`}+ placeholder="what they reach for on this axis"+ max={L.PSYCHOLOGY_DRIVE_FIELD_MAX}+ value={drives[axis]?.desire}+ onCommit={(v) => commitDrive(axis, { desire: v })}+ disabled={disabled}+ rows={1}+ />+ <PsychologyField+ id={`chr-psych-${entry.id}-${axis}-fear`}+ label={`${axis} fear`}+ placeholder="what they are bracing against on this axis"+ max={L.PSYCHOLOGY_DRIVE_FIELD_MAX}+ value={drives[axis]?.fear}+ onCommit={(v) => commitDrive(axis, { fear: v })}+ disabled={disabled}+ rows={1}+ />+ </div>+ ))}+ </div>+ <button+ type="button" onClick={() => onPatch?.({ psychology: null })}+ disabled={disabled || !hasProfile}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-port-error hover:border-port-error disabled:opacity-40"+ >+ <Trash2 size={10} /> Clear psychology profile+ </button>+ </BoxedSection>+ );+}+function IdentityPackSection({ entry, onPatch, disabled }) {const pack = entry.identityPack || {};const assets = Array.isArray(pack.assets) ? pack.assets : [];@@ -1299,6 +1494,8 @@ export default function CharacterDetailEditor({ entry, universeId = null, onPatcidPrefix={entry.id}/>+ <PsychologySection entry={entry} onPatch={onPatch} disabled={disabled} />+<VoiceCanonSection entry={entry} onPatch={onPatch} disabled={disabled} /><VoiceProfileSection universeId={universeId} entry={entry} disabled={disabled} />diff --git a/client/src/components/universe/CharacterDetailEditor.test.jsx b/client/src/components/universe/CharacterDetailEditor.test.jsxindex 24f77ce72d..1f51c96ff1 100644--- a/client/src/components/universe/CharacterDetailEditor.test.jsx+++ b/client/src/components/universe/CharacterDetailEditor.test.jsx@@ -381,3 +381,92 @@ describe('CharacterDetailEditor — production package (#5378)', () => {});});});++describe('CharacterDetailEditor — Psychology (#6414)', () => {+ const openPsychology = () => fireEvent.click(screen.getByRole('button', { name: /Psychology \(theory of control/i }));++ it('reads as unassessed on a legacy character and offers no clear action', () => {+ render(<CharacterDetailEditor entry={ARIA} characters={[ARIA]} onPatch={() => {}} />);+ expect(screen.getByRole('button', { name: /Psychology \(theory of control/i })).toHaveTextContent(/unassessed/i);+ openPsychology();+ expect(screen.getByRole('button', { name: /Clear psychology profile/i })).toBeDisabled();+ });++ it('commits an authored theory of control without disturbing the rest of the profile', () => {+ const onPatch = vi.fn();+ const entry = { ...ARIA, psychology: { strategy: 'Takes every shift nobody wants.' } };+ render(<CharacterDetailEditor entry={entry} characters={[ARIA]} onPatch={onPatch} />);+ openPsychology();+ const field = screen.getByRole('textbox', { name: /Theory of control/i });+ fireEvent.change(field, { target: { value: 'If I stay useful, nobody leaves.' } });+ fireEvent.blur(field);+ expect(onPatch).toHaveBeenCalledWith({+ psychology: {+ strategy: 'Takes every shift nobody wants.',+ theoryOfControl: 'If I stay useful, nobody leaves.',+ },+ });+ });++ it('writes a drive leaf into the nested axis it belongs to', () => {+ const onPatch = vi.fn();+ const entry = {+ ...ARIA,+ psychology: { drives: { status: { desire: 'to be counted on' } } },+ };+ render(<CharacterDetailEditor entry={entry} characters={[ARIA]} onPatch={onPatch} />);+ openPsychology();+ const fear = screen.getByRole('textbox', { name: /status fear/i });+ fireEvent.change(fear, { target: { value: 'being read as surplus' } });+ fireEvent.blur(fear);+ expect(onPatch).toHaveBeenCalledWith({+ psychology: {+ drives: { status: { desire: 'to be counted on', fear: 'being read as surplus' } },+ },+ });+ });++ it('offers an existing Lie as legacy context, explicitly NOT as the same statement', () => {+ const entry = { ...ARIA, lie: 'I only matter if I win.' };+ render(<CharacterDetailEditor entry={entry} characters={[ARIA]} onPatch={() => {}} />);+ openPsychology();+ expect(screen.getByText(/I only matter if I win\./)).toBeInTheDocument();+ expect(screen.getByText(/suggested starting point only/i)).toBeInTheDocument();+ expect(screen.getByText(/not the same sentence/i)).toBeInTheDocument();+ // The theory of control is NOT pre-filled from the Lie.+ expect(screen.getByRole('textbox', { name: /Theory of control/i })).toHaveValue('');+ });++ it('asks for an explanation only once the author rules the profile unknown', () => {+ const onPatch = vi.fn();+ const { rerender } = render(+ <CharacterDetailEditor entry={ARIA} characters={[ARIA]} onPatch={onPatch} />,+ );+ openPsychology();+ expect(screen.queryByRole('textbox', { name: /^Why$/i })).not.toBeInTheDocument();+ fireEvent.change(screen.getByRole('combobox', { name: /Assessment/i }), {+ target: { value: 'not-applicable' },+ });+ expect(onPatch).toHaveBeenCalledWith({ psychology: { assessment: 'not-applicable' } });+ rerender(+ <CharacterDetailEditor+ entry={{ ...ARIA, psychology: { assessment: 'not-applicable' } }}+ characters={[ARIA]}+ onPatch={onPatch}+ />,+ );+ expect(screen.getByRole('textbox', { name: /^Why$/i })).toBeInTheDocument();+ // A ruling with no prose leaves is still an authored profile — the section+ // must not fall back to "unassessed" and lock the clear action behind it.+ expect(screen.getByRole('button', { name: /Clear psychology profile/i })).toBeEnabled();+ });++ it('clears the whole profile through a single explicit null patch', () => {+ const onPatch = vi.fn();+ const entry = { ...ARIA, psychology: { theoryOfControl: 'Only the work is safe.' } };+ render(<CharacterDetailEditor entry={entry} characters={[ARIA]} onPatch={onPatch} />);+ openPsychology();+ fireEvent.click(screen.getByRole('button', { name: /Clear psychology profile/i }));+ expect(onPatch).toHaveBeenCalledWith({ psychology: null });+ });+});diff --git a/data.reference/prompts/stages/pipeline-character-foundation.md b/data.reference/prompts/stages/pipeline-character-foundation.mdindex b59757ce84..c1d32c766a 100644--- a/data.reference/prompts/stages/pipeline-character-foundation.md+++ b/data.reference/prompts/stages/pipeline-character-foundation.md@@ -40,6 +40,8 @@ You are the senior character architect for a long-form series. Build the human e- Preserve the `id`, name, physical identity, and established history of every supplied character. Existing canon is a constraint, not raw material to replace.- Make Ghost → Wound → Lie → Want → Need causal and specific. The Want must create external action; the Need must demand a costly contradiction of the Lie.+- Optional structured psychology (`psychology`) layers on top of that chain — never replaces it. Author it only where the supplied data supports it. `theoryOfControl` is the character's operating rule in ONE sentence, stated as they hold it and never as a restatement of the `lie` (a `lie` judges a belief; the theory states the belief as the rule they run on). `strategy` is the behavior it motivates, `protectiveBenefit` what that genuinely protects, and `presentCost` what it charges now. `drives` carries `survival`, `connection`, and `status`, each with a `desire` and a `fear`; **`status` is perceived value to a GROUP** — respect, standing, being counted — not wealth or dominance, and a non-human character gets the three axes read in terms of its own form rather than a borrowed human interior. `testingPressure` and `candidateChange` are ANTICIPATED only: what would load the theory and how it might revise. The realized, story-specific progression belongs to `characterArcs`, so never put events, issue numbers, or a sequence in the psychology profile. When the data does not support a theory of control, set `assessment` to `"unknown"` — or to `"not-applicable"` for a character with no legible interior — give the one-sentence reason in `assessmentNote`, and omit the rest of the object. An honest ruling beats an invented interior.+- The `need` is the internal alternative the Lie holds shut. It is often the Lie's direct opposite, but it may instead QUALIFY the belief; write whichever is true rather than forcing a mirror image.- Give each target character distinct values, contradictions, motivation, speech rhythm, secrets, and relationships that exert pressure in both directions. Fully author the bible profile: explicit pronouns; apparent age or age-status; speech accent or vocal quality; personality; relevant background; likes; dislikes; mannerisms; reciprocal relationships; and practical skills. "Unknown" may be a deliberate in-world age-status, but a blank is not a design choice.- Treat visual identity as canon, not decoration. `physicalDescription` must be 50–100 words of concrete, image-generation-ready detail; never use the character's name inside it. Specify apparent age range, scale/build or non-human form, surface/skin, hair and eyes when applicable, distinguishing marks, and signature attire/materials. Make `visualNotes`, `silhouetteNotes`, `postureNotes`, `visualIdentity`, and `colorPalette` mutually reinforcing and visibly distinct from every peer.- For the core cast, provide practical recurring `props`; provide `expressions`, `handGestures`, and `wardrobes` when the character's form supports them. Do not force human anatomy or clothing onto a non-human entity—use form-appropriate stats, poses, signal states, surface changes, or carried interfaces instead.@@ -89,6 +91,21 @@ Return ONLY one valid JSON object. Omit `newCharacters` when no new role is nece"expressions": [{"name": "determined", "description": "visible expression cue"}],"handGestures": [{"name": "shared stop", "description": "visible gesture cue"}],"wardrobes": [{"name": "default fieldwear", "description": "image-generation-ready outfit", "purpose": "default"}],+ "psychology": {+ "theoryOfControl": "the operating rule in one sentence, held as true by the character",+ "strategy": "the behavior the rule motivates",+ "protectiveBenefit": "what that behavior genuinely protects",+ "presentCost": "what it charges in the present",+ "testingPressure": "anticipated load on the theory; never a scene or an issue number",+ "candidateChange": "the revision the theory might undergo",+ "assessment": "omit when authored; otherwise unknown | not-applicable",+ "assessmentNote": "one-sentence reason, required when assessment is set",+ "drives": {+ "survival": {"desire": "string", "fear": "string"},+ "connection": {"desire": "string", "fear": "string"},+ "status": {"desire": "perceived value to a group", "fear": "string"}+ }+ },"arcType": "positive","secrets": ["story-active secret"]}],@@ -125,6 +142,21 @@ Return ONLY one valid JSON object. Omit `newCharacters` when no new role is nece"expressions": [{"name": "neutral", "description": "visible expression cue"}],"handGestures": [{"name": "resting pose", "description": "visible gesture cue"}],"wardrobes": [{"name": "default look", "description": "image-generation-ready outfit", "purpose": "default"}],+ "psychology": {+ "theoryOfControl": "the operating rule in one sentence, held as true by the character",+ "strategy": "the behavior the rule motivates",+ "protectiveBenefit": "what that behavior genuinely protects",+ "presentCost": "what it charges in the present",+ "testingPressure": "anticipated load on the theory; never a scene or an issue number",+ "candidateChange": "the revision the theory might undergo",+ "assessment": "omit when authored; otherwise unknown | not-applicable",+ "assessmentNote": "one-sentence reason, required when assessment is set",+ "drives": {+ "survival": {"desire": "string", "fear": "string"},+ "connection": {"desire": "string", "fear": "string"},+ "status": {"desire": "perceived value to a group", "fear": "string"}+ }+ },"arcType": "positive","secrets": ["story-active secret"]}],diff --git a/data.reference/prompts/stages/universe-character-expand.md b/data.reference/prompts/stages/universe-character-expand.mdindex 4cd9f5e3b9..1c24ed5f7b 100644--- a/data.reference/prompts/stages/universe-character-expand.md+++ b/data.reference/prompts/stages/universe-character-expand.md@@ -48,8 +48,16 @@ For every BLANK field in the character JSON above, propose a value that:- `ghost` — the past event that wounded the character (1–2 sentences). Must causally explain the Lie.- `wound` — the lasting emotional damage the Ghost left (1 sentence).- `lie` — the false belief the character holds because of the Wound. State it in ONE sentence ("I only matter if I win").- - `need` — the Truth that is the DIRECT OPPOSITE of the Lie ("I matter whether I win or lose").+ - `need` — the internal alternative the Lie is holding shut ("I matter whether I win or lose"). Often the direct opposite of the Lie, but it may instead QUALIFY the belief ("winning matters, and it is not what makes me worth keeping") — write whichever is true for this character rather than forcing a mirror image.- `want` — the concrete external goal the character pursues, which usually conflicts with the Need.+- **Psychology (`psychology`) — OPTIONAL.** A structured layer on top of the chain above, not a replacement for it. Ghost and Wound stay the origin history; Want and Need stay the conscious pursuit and the internal alternative. Propose it only for a character the universe genuinely centers, and only when the existing data supports it. Rules:+ - `theoryOfControl` — the character's operating rule in ONE sentence, stated as they would hold it, WITHOUT calling it false ("if I stay useful, nobody leaves"). This is NOT a restatement of the `lie`. A `lie` is an optional judgment about a belief; the theory of control is the belief as the rule they actually run on. If a `lie` is already populated, treat it as a starting point — never copy it verbatim, and never assert the two are identical.+ - `strategy` — the behavior the theory motivates.+ - `protectiveBenefit` — what that behavior genuinely protects them from.+ - `presentCost` — what it costs them NOW.+ - `testingPressure` / `candidateChange` — what would put the theory under load, and the revision it might undergo. Anticipated only: the story-specific progression that actually gets dramatized belongs to an authored character arc, not to this profile. Do not write events, issue numbers, or a sequence here.+ - `drives` — `survival`, `connection`, and `status`, each with a `desire` and a `fear`. **`status` means perceived value to a GROUP** — respect, standing, being counted — not wealth and not dominance. For a non-human character, interpret the three axes in terms of its own form (continuity, coupling, standing within whatever it belongs to) rather than forcing a human interior onto it.+ - `assessment` — omit it for an ordinary authored profile. Use `"unknown"` when the supplied data does not support a theory of control, or `"not-applicable"` when the character has no legible interior at all (a hive, a weather front, an unpersoned system) — and in EITHER case put your one-sentence reason in `assessmentNote` and omit the rest of the object. An honest "unknown" beats an invented interior.- `arcType` — one of `positive` (overcomes the Lie, embraces the Truth), `negative` (consumed by the Lie), or `flat` (already knows the Truth; changes the world instead). Omit if unclear.- `sliders` — rate `proactivity`, `likability`, `competence` each 1–10. Rule: HIGH (≥7) on at least TWO, OR high on one with clear room to grow. All-low reads boring; all-high-from-the-start reads as a Mary Sue. Omit for a bit-player.- `secrets` — 2+ things this character hides (from others or themselves). Short prose items.@@ -90,6 +98,21 @@ Return ONLY valid JSON, no markdown fence, no commentary. Include ONLY the keys"lie": "string","want": "string","need": "string",+ "psychology": {+ "theoryOfControl": "string",+ "strategy": "string",+ "protectiveBenefit": "string",+ "presentCost": "string",+ "testingPressure": "string",+ "candidateChange": "string",+ "assessment": "assessed | unknown | not-applicable",+ "assessmentNote": "string — required when assessment is unknown or not-applicable",+ "drives": {+ "survival": {"desire": "string", "fear": "string"},+ "connection": {"desire": "string", "fear": "string"},+ "status": {"desire": "string", "fear": "string"}+ }+ },"arcType": "positive | negative | flat","sliders": {"proactivity": 1, "likability": 1, "competence": 1},"secrets": ["string"],diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex 0a74a93ecf..0d7a27fc6b 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -252,7 +252,8 @@ The task's `depth` parameter picks what "described" means, percharacter-sheet expand prompt fills: the visual set (silhouette, posture,palette, props, expressions, hand gestures, wardrobes), the novelist set(likes, mannerisms, relationships, skills), and the Ghost → Wound → Lie → Want- → Need framework with its arc type and sliders. `full` is the default because+ → Need framework with its arc type, sliders, and the optional psychology+ profile (theory of control + survival / connection / status drives). `full` is the default becausethe job exists for the sheet — a cast member with a one-line description stillrenders inconsistently from panel to panel.diff --git a/scripts/migrations/027-text-stage-prompts-entities-summary.js b/scripts/migrations/027-text-stage-prompts-entities-summary.jsindex de8574304f..277bcb1ffe 100644--- a/scripts/migrations/027-text-stage-prompts-entities-summary.js+++ b/scripts/migrations/027-text-stage-prompts-entities-summary.js@@ -73,7 +73,7 @@ export const NEW_SHIPPED_MD5 = {'pipeline-prose.md': '4cb3ef48309f3673570cf80e4d544b54', // post-169 (cross-issue continuity)'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77', // post-128 (canonical scene list)'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)- 'universe-character-expand.md': '924fe8836f3014873d1789e98e997db2', // post-257 (complete expand fields)+ 'universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd', // post-257 (complete expand fields)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/171-character-framework-prompt.js b/scripts/migrations/171-character-framework-prompt.jsindex 6fab6af0fe..9125275d78 100644--- a/scripts/migrations/171-character-framework-prompt.js+++ b/scripts/migrations/171-character-framework-prompt.js@@ -35,7 +35,7 @@ export const ACCEPTED_OLD_MD5 = {// Post-change shipped hash (character framework fields added).export const NEW_SHIPPED_MD5 = {- 'universe-character-expand.md': '924fe8836f3014873d1789e98e997db2', // post-257 (complete expand fields)+ 'universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd', // post-257 (complete expand fields)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/240-character-foundation-exhaustive-cast.js b/scripts/migrations/240-character-foundation-exhaustive-cast.jsindex 0556d5a6bc..46013c5cf4 100644--- a/scripts/migrations/240-character-foundation-exhaustive-cast.js+++ b/scripts/migrations/240-character-foundation-exhaustive-cast.js@@ -19,7 +19,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-character-foundation.md': 'b7d2bac347e11171606f4c6acfcd32e1', // post-256 (series-linked cast)+ 'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4', // post-256 (series-linked cast)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/243-post-arc-character-transition-ownership.js b/scripts/migrations/243-post-arc-character-transition-ownership.jsindex b04bc2ce84..cf89b35138 100644--- a/scripts/migrations/243-post-arc-character-transition-ownership.js+++ b/scripts/migrations/243-post-arc-character-transition-ownership.js@@ -18,7 +18,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-character-foundation.md': 'b7d2bac347e11171606f4c6acfcd32e1', // post-256 (series-linked cast)+ 'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4', // post-256 (series-linked cast)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/255-character-visual-foundation.js b/scripts/migrations/255-character-visual-foundation.jsindex 8db265969a..96bb894537 100644--- a/scripts/migrations/255-character-visual-foundation.js+++ b/scripts/migrations/255-character-visual-foundation.js@@ -24,7 +24,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-character-foundation.md': 'b7d2bac347e11171606f4c6acfcd32e1', // post-256 (series-linked cast)+ 'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4', // post-256 (series-linked cast)'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410', // post-256 (series-linked cast)};diff --git a/scripts/migrations/256-series-linked-character-profiles.js b/scripts/migrations/256-series-linked-character-profiles.jsindex f73bb5ea3c..1643e4a3c8 100644--- a/scripts/migrations/256-series-linked-character-profiles.js+++ b/scripts/migrations/256-series-linked-character-profiles.js@@ -16,7 +16,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-character-foundation.md': 'b7d2bac347e11171606f4c6acfcd32e1',+ 'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4','pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410',};diff --git a/scripts/migrations/257-complete-character-expand-fields.js b/scripts/migrations/257-complete-character-expand-fields.jsindex a69b929a94..9ec9fc5ead 100644--- a/scripts/migrations/257-complete-character-expand-fields.js+++ b/scripts/migrations/257-complete-character-expand-fields.js@@ -13,7 +13,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'universe-character-expand.md': '924fe8836f3014873d1789e98e997db2',+ 'universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/360-character-psychology-prompts.js b/scripts/migrations/360-character-psychology-prompts.jsnew file mode 100644index 0000000000..54b74a429d--- /dev/null+++ b/scripts/migrations/360-character-psychology-prompts.js@@ -0,0 +1,28 @@+/**+ * Teach the character prompts the optional psychology profile (#6414):+ * a one-sentence theory of control, the strategy it motivates, what it+ * protects, what it costs, and the survival / connection / status drives it+ * serves — plus the rule that a `lie` is never restated as the theory and that+ * an honest `unknown` beats an invented interior.+ */+import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ "universe-character-expand.md": [+ "924fe8836f3014873d1789e98e997db2"+ ],+ "pipeline-character-foundation.md": [+ "b7d2bac347e11171606f4c6acfcd32e1"+ ]+};+export const NEW_SHIPPED_MD5 = {+ "universe-character-expand.md": "961b73ba6e50df5d49f0cc76505e50bd",+ "pipeline-character-foundation.md": "c606061954b23a9957c68dd068b54dc4"+};+const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,+ label: 'character psychology profile',+ customizedHint: (filename) => ` Merge the psychology (theory of control + survival/connection/status drives) guidance and output keys from data.reference/prompts/stages/${filename}.`,+});+export { applyMigration };+export default { up };diff --git a/scripts/migrations/360-character-psychology-prompts.test.js b/scripts/migrations/360-character-psychology-prompts.test.jsnew file mode 100644index 0000000000..4e36105476--- /dev/null+++ b/scripts/migrations/360-character-psychology-prompts.test.js@@ -0,0 +1,6 @@+import { describe } from 'vitest';+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './360-character-psychology-prompts.js';+import { runPromptMigrationTests } from './_testHelpers.js';+describe('migration 360 — character psychology prompts', () => {+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-360-' });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 1be7b5dd9e..a8ed1341ae 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -38,7 +38,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],- 'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139', '67b6e73ed47f318451a730088b4cff14', '177b6e4e8bdf445308cf8ac423cd5ad8'],+ 'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139', '67b6e73ed47f318451a730088b4cff14', '177b6e4e8bdf445308cf8ac423cd5ad8', '924fe8836f3014873d1789e98e997db2'],'story-builder-idea-expand.md': ['778c86e2caa120856c36e4d5a4da3355', 'a23939626a226f7420cebfb45d47950c'],'pipeline-editorial-analysis.md': ['14d9879697c66d51830cc798040d5369'],'pipeline-manuscript-completeness.md': ['4f2b95778aed85f5fc461d71eb461b79', 'e6858c74ab2cead752d388e3f428406c', '1ee5ac936fbf1d365e0eaea99bcf1e77', 'cec8faeb75dfff74e41b8221145c2e92'],@@ -51,7 +51,7 @@ const EXPECTED_STAGE_OLD = {'cd-treatment.md': ['2ffa482e7bfb6fe8b7224505fedbf712', '16d0ef6a7fd2533719a846019122ebee', '95b7685690ecfee4f682b0293b790277'],'cd-plan.md': ['3ce871196a8fd04781b71b6780e89c86', '0768d6809645c2c1fe73cacae9740fe9', 'ef0d96f6ebde43af6c4579969d31cfb7'],'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d', '21352c21ed6d4edb7a4b7c32704eff55'],- 'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c', 'cda34127b40754ddbcc8544e3d82572b', 'd6c449c06de73a0868141c899b26e52c', '04419e382f3b46ed92bfaaa1d4f39e13'],+ 'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c', 'cda34127b40754ddbcc8544e3d82572b', 'd6c449c06de73a0868141c899b26e52c', '04419e382f3b46ed92bfaaa1d4f39e13', 'b7d2bac347e11171606f4c6acfcd32e1'],'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f'],'pipeline-observer.md': ['f3dc51ac077050a887c2161ee7438181'],'pipeline-self-improve.md': ['ed0b0df42e0690d515b8dd88911931e4'],@@ -83,7 +83,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4','cos-agent-briefing.md': 'a01c81d3a7f4ac0ca9e8d5137735c0e3',- 'universe-character-expand.md': '924fe8836f3014873d1789e98e997db2',+ 'universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd','story-builder-idea-expand.md': 'c12d76fefaaded2838023065bfc94bb0','pipeline-editorial-analysis.md': 'daeb02bd54b0c099b21af659c6298cfe','pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',@@ -95,7 +95,7 @@ const EXPECTED_STAGE_NEW = {'cd-treatment.md': 'd940eadfb406ce584f0e244032f33382','cd-plan.md': '41a61590896d1327df2c6915557361de','pipeline-series-generate.md': '136a21435aba2b2b212883750040b986',- 'pipeline-character-foundation.md': 'b7d2bac347e11171606f4c6acfcd32e1',+ 'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4','pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410','pipeline-observer.md': '29e0212d2252b1be3278f20e2959eb8e','pipeline-self-improve.md': '95b378832ff78e5976a6a63fcf328090',diff --git a/server/lib/bibleLimits.js b/server/lib/bibleLimits.jsindex 4810dfbf93..15ca6ec613 100644--- a/server/lib/bibleLimits.js+++ b/server/lib/bibleLimits.js@@ -50,6 +50,27 @@ export const BIBLE_LIMITS = Object.freeze({LIE_MAX: 600,WANT_MAX: 600,NEED_MAX: 600,+ // Character psychology (#6414). OPTIONAL structured layer on top of the+ // Ghost → Wound → Lie → Want → Need chain above: the character's operating+ // rule ('theory of control'), the strategy it motivates, what it protects,+ // what it costs now, and the survival / connection / status drives it+ // serves. Absent on every pre-#6414 record — the sanitizer returns null when+ // nothing is authored, so the legacy character shape round-trips unchanged.+ // 'Status' here is perceived value to a group, not wealth or dominance.+ THEORY_OF_CONTROL_MAX: 400,+ PSYCHOLOGY_STRATEGY_MAX: 800,+ PSYCHOLOGY_PROTECTION_MAX: 600,+ PSYCHOLOGY_COST_MAX: 600,+ // Anticipated pressure on the theory and the change it could produce. Kept+ // in the PROFILE deliberately: a realized, story-specific progression is an+ // authored arc (series.characterArcs), not a character-sheet field.+ PSYCHOLOGY_PRESSURE_MAX: 800,+ PSYCHOLOGY_CHANGE_MAX: 800,+ // Author escape hatch: 'unknown' / 'not-applicable' with an explanation, so a+ // deliberately opaque or nonhuman character reads as ASSESSED, not unfilled.+ PSYCHOLOGY_NOTE_MAX: 800,+ // Per-drive desire + fear.+ PSYCHOLOGY_DRIVE_FIELD_MAX: 400,// Secrets the character keeps (≥2 encouraged in the prompt). Short prose// items, capped per-item and per-character like other string lists.SECRET_MAX: 600,diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 3760d4eb77..bf41872f64 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -70,7 +70,14 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// v10 = character `voiceCanon` and `identityPack` added (#5378). These are// portable, federated production-canon fields; a ≤v9 peer would sanitize// them away and LWW the loss back after an unrelated Universe edit.- universes: 10,+ // v11 = character `psychology` added (#6414) — the optional structured+ // theory-of-control + survival/connection/status drive profile. Additive and+ // gracefully degrading, but version-gated for the same reason as v6–v10: a+ // ≤v10 peer that re-sanitizes a universe through its psychology-unaware+ // `sanitizeCharacter` would strip the profile and last-writer-wins the loss+ // back onto the newer peer. Per-category gate → only universe sync pauses+ // with old peers.+ universes: 11,// v1 = post-split. Migrations 035/036 introduced the pipeline collection// layout for issues and series.// v2 = `stages.audio.audioMode` + `stages.audio.cues[]` added (whole-episodediff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex 585fcaba66..432139e783 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -20,10 +20,11 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {// deliberate two-file edit.// v6 = canon characters gained relationshipLinks[] (#1287); v7 = canon// objects gained attachments[] (#1288); v8 adds styleReferences[]; v9 adds- // moodBoardId (#4188); v10 adds character production packages (#5378).+ // moodBoardId (#4188); v10 adds character production packages (#5378);+ // v11 adds the optional character psychology profile (#6414).// These are additive + version-gated so an older peer// cannot strip-then-LWW them.- expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(10);+ expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(11);});it('declares pipeline collection layout versions', () => {@@ -58,14 +59,14 @@ describe('buildPortosMeta', () => {it('returns { portosVersion, schemaVersions } with the live registry', async () => {const meta = await buildPortosMeta();expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);- expect(meta.schemaVersions.universes).toBe(10);+ expect(meta.schemaVersions.universes).toBe(11);expect(meta.schemaVersions.pipelineIssues).toBe(3);expect(meta.schemaVersions.pipelineSeries).toBe(12);});it('overrides merge into schemaVersions', async () => {const meta = await buildPortosMeta({ schemaVersions: { future: 1 } });- expect(meta.schemaVersions.universes).toBe(10);+ expect(meta.schemaVersions.universes).toBe(11);expect(meta.schemaVersions.future).toBe(1);});});diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 20dec0155a..2caa3b371b 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -110,6 +110,25 @@ const PLACE_TIME_OF_DAY_SET = new Set(PLACE_TIME_OF_DAY);export const CHARACTER_ARC_TYPES = Object.freeze(['positive', 'negative', 'flat']);const CHARACTER_ARC_TYPE_SET = new Set(CHARACTER_ARC_TYPES);+// Character psychology (#6414). An OPTIONAL layer over the existing framework:+// Ghost/Wound stay the origin history, Want/Need stay the conscious pursuit and+// the internal alternative, and the Lie stays an optional JUDGMENT about a+// belief. `theoryOfControl` is something else — the character's operating rule+// ('if I stay useful, nobody leaves'), stated without calling it false. The two+// are related but never asserted identical, and the Need may qualify a belief+// 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']);+const PSYCHOLOGY_ASSESSMENT_SET = new Set(PSYCHOLOGY_ASSESSMENTS);+const trimEnum = (raw, allowed) => {if (typeof raw !== 'string') return null;const trimmed = raw.trim();@@ -142,7 +161,7 @@ export const BIBLE_KINDS = Object.freeze(Object.values(BIBLE_KIND));// `existing<X>Json` prompt variable (bibleExtractor) and into the script// stage's bibles context (evaluator). Excludes ids/timestamps/source/notes.export const PROMPT_FIELDS = Object.freeze({- [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern', 'visualNotes', 'physicalDescription', 'personality', 'background', 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity', 'motivations', 'ghost', 'wound', 'lie', 'want', 'need', 'arcType', 'sliders', 'secrets', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills', 'stats', 'colorPalette', 'props', 'expressions', 'handGestures', 'voiceId', 'wardrobes', 'prompt', 'tags'],+ [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern', 'visualNotes', 'physicalDescription', 'personality', 'background', 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity', 'motivations', 'ghost', 'wound', 'lie', 'want', 'need', 'psychology', 'arcType', 'sliders', 'secrets', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills', 'stats', 'colorPalette', 'props', 'expressions', 'handGestures', 'voiceId', 'wardrobes', 'prompt', 'tags'],[BIBLE_KIND.PLACE]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'intExt', 'timeOfDay', 'recurringDetails', 'prompt', 'tags'],[BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance', 'prompt', 'tags'],});@@ -406,6 +425,48 @@ function sanitizeVoiceCanon(raw) {};}+/**+ * Optional structured psychology profile (#6414). Returns null when nothing is+ * authored so a pre-#6414 character round-trips with no `psychology` key at+ * all — which is also how an explicit CLEAR works: a PATCH carrying+ * `psychology: null` (or an all-blank object) drops the field rather than+ * persisting an empty husk that would read as 'assessed'.+ *+ * `drives` is always materialized with all three axes so a partial fill has a+ * stable slot to write into; the whole object still collapses to null when+ * every leaf is blank.+ */+function sanitizeCharacterPsychology(raw) {+ if (!isPlainObject(raw)) return null;+ const rawDrives = isPlainObject(raw.drives) ? raw.drives : {};+ const drives = {};+ let anyDrive = false;+ for (const axis of PSYCHOLOGY_DRIVE_AXES) {+ const row = isPlainObject(rawDrives[axis]) ? rawDrives[axis] : {};+ const desire = trimTo(row.desire, BIBLE_LIMITS.PSYCHOLOGY_DRIVE_FIELD_MAX);+ const fear = trimTo(row.fear, BIBLE_LIMITS.PSYCHOLOGY_DRIVE_FIELD_MAX);+ if (desire || fear) anyDrive = true;+ drives[axis] = { desire, fear };+ }+ const out = {+ theoryOfControl: trimTo(raw.theoryOfControl, BIBLE_LIMITS.THEORY_OF_CONTROL_MAX),+ strategy: trimTo(raw.strategy, BIBLE_LIMITS.PSYCHOLOGY_STRATEGY_MAX),+ protectiveBenefit: trimTo(raw.protectiveBenefit, BIBLE_LIMITS.PSYCHOLOGY_PROTECTION_MAX),+ presentCost: trimTo(raw.presentCost, BIBLE_LIMITS.PSYCHOLOGY_COST_MAX),+ // Anticipated, not realized: what would test the theory and what it could+ // become. The delivered progression belongs to an authored arc.+ testingPressure: trimTo(raw.testingPressure, BIBLE_LIMITS.PSYCHOLOGY_PRESSURE_MAX),+ candidateChange: trimTo(raw.candidateChange, BIBLE_LIMITS.PSYCHOLOGY_CHANGE_MAX),+ assessment: trimEnum(raw.assessment, PSYCHOLOGY_ASSESSMENT_SET),+ assessmentNote: trimTo(raw.assessmentNote, BIBLE_LIMITS.PSYCHOLOGY_NOTE_MAX),+ drives,+ };+ const anyText = out.theoryOfControl || out.strategy || out.protectiveBenefit+ || out.presentCost || out.testingPressure || out.candidateChange+ || out.assessmentNote;+ return anyText || anyDrive || out.assessment ? out : null;+}+function sanitizeIdentityPack(raw, imageRefs) {if (!isPlainObject(raw)) return null;const seen = new Set();@@ -453,13 +514,30 @@ export function characterIdentityPackReadiness(character) {};}+// Additive character fields an older peer's sanitizer cannot represent, keyed+// by the `universes` wire version that introduced each one. A sender AT or+// ABOVE that version omitting the field means the author cleared it; a sender+// BELOW it omitted the field only because its code has no slot for it.+const ADDITIVE_CHARACTER_FIELD_VERSIONS = Object.freeze({+ // v10 — portable production canon (#5378).+ voiceCanon: 10,+ identityPack: 10,+ // v11 — optional structured psychology profile (#6414).+ psychology: 11,+});+/**- * Preserve v10 character production fields when an older peer wins LWW with- * a character shape that could not represent them. A v10-aware sender's- * omission is an intentional clear and must pass through unchanged.+ * Preserve additive character fields when an older peer wins LWW with a+ * character shape that could not represent them. Each field is restored ONLY+ * from a sender behind the version that introduced it — a version-aware+ * sender's omission is an intentional clear and must pass through unchanged.*/-export function preserveLegacyCharacterProductionPackages(remoteCharacters, localCharacters, senderUniversesVersion) {- if ((Number(senderUniversesVersion) || 0) >= 10+export function preserveLegacyCharacterFields(remoteCharacters, localCharacters, senderUniversesVersion) {+ const sender = Number(senderUniversesVersion) || 0;+ const unrepresentable = Object.entries(ADDITIVE_CHARACTER_FIELD_VERSIONS)+ .filter(([, since]) => sender < since)+ .map(([field]) => field);+ if (unrepresentable.length === 0|| !Array.isArray(remoteCharacters)|| !Array.isArray(localCharacters)) return remoteCharacters;const localById = new Map(@@ -468,11 +546,11 @@ export function preserveLegacyCharacterProductionPackages(remoteCharacters, locareturn remoteCharacters.map((character) => {const localCharacter = localById.get(character?.id);if (!localCharacter) return character;- return {- ...character,- ...(!character.voiceCanon && localCharacter.voiceCanon ? { voiceCanon: localCharacter.voiceCanon } : {}),- ...(!character.identityPack && localCharacter.identityPack ? { identityPack: localCharacter.identityPack } : {}),- };+ const restored = {};+ for (const field of unrepresentable) {+ if (!character?.[field] && localCharacter[field]) restored[field] = localCharacter[field];+ }+ return Object.keys(restored).length ? { ...character, ...restored } : character;});}@@ -931,6 +1009,7 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,const imageRefs = cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX);const voiceCanon = sanitizeVoiceCanon(raw.voiceCanon);const identityPack = sanitizeIdentityPack(raw.identityPack, imageRefs);+ const psychology = sanitizeCharacterPsychology(raw.psychology);return {id: ensureId(raw.id, idPrefix),name,@@ -972,6 +1051,12 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,lie: trimTo(raw.lie, BIBLE_LIMITS.LIE_MAX),want: trimTo(raw.want, BIBLE_LIMITS.WANT_MAX),need: trimTo(raw.need, BIBLE_LIMITS.NEED_MAX),+ // Optional structured psychology (#6414). Layered on the chain above, not+ // a replacement for it: Ghost/Wound remain the origin history and+ // Want/Need the conscious pursuit + internal alternative. Absent (no key)+ // on every record that has not been assessed, so legacy characters stay+ // valid and visibly unfilled rather than silently inheriting a profile.+ ...(psychology ? { psychology } : {}),// Declared arc type — null (unset) unless it's one of the three known// values, so a legacy record with no arc type stays absent.arcType: trimEnum(raw.arcType, CHARACTER_ARC_TYPE_SET),@@ -1348,6 +1433,10 @@ const MERGE_CONFIG = Object.freeze({'stats', 'colorPalette', 'props', 'expressions', 'handGestures',// Character framework (CWQE Phase 10, #2175) — fill only when blank.'ghost', 'wound', 'lie', 'want', 'need', 'arcType', 'secrets',+ // Optional psychology profile (#6414). Whole-object granularity, like+ // `wardrobes`: the extractor may author one on a character that has none,+ // and never touches a profile the writer has already started.+ 'psychology',],keyFields: [{ field: 'name', normalize: normalizeBibleName },diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex 9029c76b1c..3c83610fcb 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -41,7 +41,7 @@ const {canonHasRevealGated,revealGatedCanonRows,characterIdentityPackReadiness,- preserveLegacyCharacterProductionPackages,+ preserveLegacyCharacterFields,} = storyBible;const WORK_ID = 'wr-work-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';@@ -381,12 +381,44 @@ describe('storyBible — sanitizeCharacter', () => {identityPack: { assets: [{ role: 'neutral', imageRef: 'n.png', approved: true }] },}];const remote = [{ id: 'chr-1', name: 'A from peer' }];- expect(preserveLegacyCharacterProductionPackages(remote, local, 9)[0]).toMatchObject({+ expect(preserveLegacyCharacterFields(remote, local, 9)[0]).toMatchObject({name: 'A from peer',voiceCanon: local[0].voiceCanon,identityPack: local[0].identityPack,});- expect(preserveLegacyCharacterProductionPackages(remote, local, 10)).toEqual(remote);+ expect(preserveLegacyCharacterFields(remote, local, 10)).toEqual(remote);+ });+ });++ describe('psychology profile (#6414)', () => {+ it('preserves a profile from a pre-v11 peer but honors a v11 clear', () => {+ const local = [{+ id: 'chr-1', name: 'A',+ psychology: { theoryOfControl: 'If I stay useful, nobody leaves.' },+ }];+ const remote = [{ id: 'chr-1', name: 'A from peer' }];+ // A peer whose sanitizer has no psychology slot omitted it because it+ // COULD NOT carry it — restoring is what stops its LWW write from+ // deleting a profile it never saw.+ expect(preserveLegacyCharacterFields(remote, local, 10)[0]).toMatchObject({+ name: 'A from peer',+ psychology: local[0].psychology,+ });+ // A v11-aware peer omitting it means the author cleared it.+ expect(preserveLegacyCharacterFields(remote, local, 11)).toEqual(remote);+ });++ it('restores ONLY the fields the sender could not represent', () => {+ const local = [{+ id: 'chr-1', name: 'A',+ voiceCanon: { version: 2, approved: true },+ psychology: { theoryOfControl: 'Only the work is safe.' },+ }];+ // A v10 sender understands voiceCanon (so its omission is a clear) but+ // not psychology (so its omission is a gap).+ const restored = preserveLegacyCharacterFields([{ id: 'chr-1', name: 'A' }], local, 10)[0];+ expect(restored.voiceCanon).toBeUndefined();+ expect(restored.psychology).toEqual(local[0].psychology);});});diff --git a/server/lib/universeBibleCompleteness.js b/server/lib/universeBibleCompleteness.jsindex 550811259d..ba28a3b997 100644--- a/server/lib/universeBibleCompleteness.js+++ b/server/lib/universeBibleCompleteness.js@@ -24,7 +24,7 @@* scan, so the two are deliberately one list rather than two that agree today.*/-import { BIBLE_KEYS, isBlank } from './storyBible.js';+import { BIBLE_KEYS, isBlank, PSYCHOLOGY_DRIVE_AXES } from './storyBible.js';/** Depth vocabulary. `core` = renderable at all; `full` = the whole sheet. */export const BIBLE_DESCRIBE_DEPTHS = Object.freeze(['core', 'full']);@@ -67,7 +67,10 @@ export const BIBLE_EXPAND_FIELDS = Object.freeze({'wardrobes', 'secrets',]),enums: Object.freeze(['arcType']),- objects: Object.freeze(['sliders']),+ // `psychology` (#6414) — the optional theory-of-control + drives profile.+ // Structured, so it merges leaf-by-leaf like `sliders` rather than as one+ // opaque string; `characterPsychologyIsBlank` below is its filled rule.+ objects: Object.freeze(['sliders', 'psychology']),}),place: Object.freeze({strings: Object.freeze(['description', 'palette', 'era', 'weather', 'recurringDetails']),@@ -132,9 +135,32 @@ export function bibleFieldIsBlank(entry, field) {// rated, so plain presence would report it filled the moment the sanitizer// materialized it.if (field === 'sliders') return SLIDER_AXES.some((axis) => entry?.sliders?.[axis] == null);+ // `psychology` is absent entirely until authored, and materializes all three+ // drive slots the moment any leaf is filled — so it needs its own rule too.+ if (field === 'psychology') return characterPsychologyIsBlank(entry?.psychology);return isBlank(entry?.[field]);}+/**+ * Whether a character's psychology profile (#6414) still counts as unassessed.+ *+ * Presence alone is not enough (same reason `sliders` needs a rule): the+ * sanitizer materializes all three drive slots as soon as ANY leaf is authored.+ * An explicit `unknown` / `not-applicable` ruling WITH the author's+ * explanation is a real assessment, not a gap — that is what lets a+ * deliberately opaque or nonhuman character be complete without inventing a+ * human interior for it.+ */+export function characterPsychologyIsBlank(psychology) {+ if (!psychology || typeof psychology !== 'object' || Array.isArray(psychology)) return true;+ if (psychology.assessment === 'unknown' || psychology.assessment === 'not-applicable') {+ return isBlank(psychology.assessmentNote);+ }+ if (isBlank(psychology.theoryOfControl)) return true;+ return PSYCHOLOGY_DRIVE_AXES.some((axis) => isBlank(psychology.drives?.[axis]?.desire)+ || isBlank(psychology.drives?.[axis]?.fear));+}+/** Normalize an untrusted depth param to a known depth, defaulting to `full`. */export const normalizeDescribeDepth = (depth) =>(BIBLE_DESCRIBE_DEPTHS.includes(depth) ? depth : 'full');diff --git a/server/lib/universeBibleCompleteness.test.js b/server/lib/universeBibleCompleteness.test.jsindex 7dcad61d6b..95c895f9c9 100644--- a/server/lib/universeBibleCompleteness.test.js+++ b/server/lib/universeBibleCompleteness.test.js@@ -19,6 +19,14 @@ const describedCharacter = () => {for (const field of groups.lists) entry[field] = [{ name: 'x' }];entry.arcType = 'positive';entry.sliders = { proactivity: 7, likability: 6, competence: 8 };+ entry.psychology = {+ theoryOfControl: 'if I stay useful, nobody leaves',+ drives: {+ survival: { desire: 'a roof that is hers', fear: 'being turned out' },+ connection: { desire: 'to be kept', fear: 'being easy to replace' },+ status: { desire: 'to be counted on', fear: 'being seen as surplus' },+ },+ };return entry;};diff --git a/server/lib/universeMarkdown.js b/server/lib/universeMarkdown.jsindex 3d02ee48c8..24e799d1be 100644--- a/server/lib/universeMarkdown.js+++ b/server/lib/universeMarkdown.js@@ -13,7 +13,7 @@ const CANON_ENTRY_FIELD_ORDER = Object.freeze({'speechPattern', 'visualNotes', 'physicalDescription', 'personality','background', 'silhouetteNotes', 'postureNotes', 'specialTraits','visualIdentity', 'motivations', 'ghost', 'wound', 'lie', 'want', 'need',- 'arcType', 'sliders', 'secrets', 'likes', 'dislikes', 'mannerisms',+ 'psychology', 'arcType', 'sliders', 'secrets', 'likes', 'dislikes', 'mannerisms','relationships', 'skills', 'stats', 'colorPalette', 'props','expressions', 'handGestures', 'voiceId', 'wardrobes', 'tags', 'prompt','notes', 'evidence', 'firstAppearance', 'imageRefs', 'primaryImageRef',diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 6b35b724fe..d8ba40b171 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -163,19 +163,19 @@ describe('dataSync — universe category', () => {const snap = await dataSync.getSnapshot('universe');expect(snap.portosMeta).toBeDefined();expect(typeof snap.portosMeta.portosVersion).toBe('string');- expect(snap.portosMeta.schemaVersions.universes).toBe(10);+ expect(snap.portosMeta.schemaVersions.universes).toBe(11);});it('applyRemote rejects when sender schemaVersions are AHEAD of local code', async () => {writeUniverseState({ universes: [], runs: [] });const result = await dataSync.applyRemote('universe', {universes: [{ id: 'u-new', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }],- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 11 } } });+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 12 } } });expect(result.applied).toBe(false);expect(result.count).toBe(0);expect(result.blockedBySchema).toBeDefined();expect(result.blockedBySchema.ahead).toEqual([- { category: 'universes', senderV: 11, receiverV: 10 },+ { category: 'universes', senderV: 12, receiverV: 11 },]);expect(result.blockedBySchema.senderPortosVersion).toBe('99.0.0');// Nothing was written.diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex 12517924d3..a459200517 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -532,6 +532,11 @@ const REPAIRABLE_CHARACTER_FIELDS = Object.freeze([...VISUAL_FOUNDATION_LIST_FIELDS,'arcType','secrets',+ // Optional structured psychology (#6414). Allowlisted so a repair proposal+ // that authors one is applied rather than silently dropped; it is NOT part+ // of `hasCompleteFramework` below, so its absence never by itself makes an+ // existing cast read as incomplete and schedule a repair run.+ 'psychology','personality','background','relationships',@@ -943,7 +948,13 @@ async function repairCharacters(series, issues, universe, finding, options) {const next = { ...character };for (const field of REPAIRABLE_CHARACTER_FIELDS) {const value = sanitized[field];- const authored = Array.isArray(value) ? value.length > 0 : !isBlankString(value);+ // Object-valued fields (`psychology`) are authored when the sanitizer+ // returned one at all — it collapses an empty proposal to null/absent.+ const authored = Array.isArray(value)+ ? value.length > 0+ : (value && typeof value === 'object')+ ? Object.keys(value).length > 0+ : !isBlankString(value);if (!authored || JSON.stringify(value) === JSON.stringify(character[field])) continue;next[field] = value;updatedFields.add(field);diff --git a/server/services/pipeline/foundationJudgeContext.js b/server/services/pipeline/foundationJudgeContext.jsindex ebfc019c04..af78a50b78 100644--- a/server/services/pipeline/foundationJudgeContext.js+++ b/server/services/pipeline/foundationJudgeContext.js@@ -10,6 +10,7 @@ import { composeStyleNotes } from '../../lib/styleGuide.js';import { renderCharacterArcsForPrompt } from '../../lib/seriesCharacterArc.js';import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';+import { PSYCHOLOGY_DRIVE_AXES } from '../../lib/storyBible.js';// The character-framework subset the character dimension scores (Ghost → Wound →// Lie → Want → Need chain + secrets + arc fields). Shared by the hash projection@@ -30,11 +31,36 @@ export const VISUAL_FOUNDATION_STRING_FIELDS = Object.freeze([]);export const VISUAL_FOUNDATION_LIST_FIELDS = Object.freeze(['colorPalette']);+// The optional psychology profile (#6414). Projected ONLY when the character+// actually carries one: including an empty husk would change the foundation+// hash of every pre-#6414 character on this install and invalidate their+// scores for a field nobody has authored yet.+export function pickPsychologyFields(c) {+ const p = c?.psychology;+ if (!p || typeof p !== 'object' || Array.isArray(p)) return null;+ return {+ theoryOfControl: p.theoryOfControl || '',+ strategy: p.strategy || '',+ protectiveBenefit: p.protectiveBenefit || '',+ presentCost: p.presentCost || '',+ testingPressure: p.testingPressure || '',+ candidateChange: p.candidateChange || '',+ assessment: p.assessment || '',+ assessmentNote: p.assessmentNote || '',+ drives: Object.fromEntries(PSYCHOLOGY_DRIVE_AXES.map((axis) => [axis, {+ desire: p.drives?.[axis]?.desire || '',+ fear: p.drives?.[axis]?.fear || '',+ }])),+ };+}+export function pickFrameworkFields(c) {const out = {};for (const f of FRAMEWORK_STRING_FIELDS) out[f] = c?.[f] || '';out.arcType = c?.arcType || '';out.secrets = Array.isArray(c?.secrets) ? c.secrets : [];+ const psychology = pickPsychologyFields(c);+ if (psychology) out.psychology = psychology;return out;}@@ -260,7 +286,28 @@ export function renderCharacterLine(c, { core = false } = {}) {...VISUAL_FOUNDATION_STRING_FIELDS.map((field) => `${field}: ${visualString(field)}`),...VISUAL_FOUNDATION_LIST_FIELDS.map((field) => `${field}: ${visualList(field)}`),].join(' | ');- return `- ${core ? '[CORE] ' : ''}**${c?.name || 'Unnamed'}**${role} — dramatic framework: ${framework} | profile: ${profile} | arcType: ${c?.arcType || '—'} | secrets: ${secrets || '—'} | visual foundation: ${visual}`;+ // Optional psychology profile (#6414). Appended only when authored — an+ // 'unassessed' marker on every legacy character would add a line of noise per+ // cast member to a prompt this module works hard to keep inside its budget.+ const psychology = pickPsychologyFields(c);+ const drives = psychology+ ? PSYCHOLOGY_DRIVE_AXES+ .map((axis) => `${axis} desire: ${concise(psychology.drives[axis].desire, 120)}, fear: ${concise(psychology.drives[axis].fear, 120)}`)+ .join(' | ')+ : '';+ const ruling = psychology?.assessment+ ? ` | assessment: ${psychology.assessment} (${concise(psychology.assessmentNote, 200)})`+ : '';+ const control = psychology+ ? [+ `theory: ${concise(psychology.theoryOfControl, 240)}`,+ `strategy: ${concise(psychology.strategy, 240)}`,+ `protects: ${concise(psychology.protectiveBenefit, 200)}`,+ `costs: ${concise(psychology.presentCost, 200)}`,+ `drives: ${drives}`,+ ].join(' | ')+ : '';+ return `- ${core ? '[CORE] ' : ''}**${c?.name || 'Unnamed'}**${role} — dramatic framework: ${framework} | profile: ${profile} | arcType: ${c?.arcType || '—'} | secrets: ${secrets || '—'}${control ? ` | control: ${control}` : ''}${ruling} | visual foundation: ${visual}`;}const joinedLength = (lines) => lines.reduce((total, line) => total + line.length + 1, 0);diff --git a/server/services/pipeline/foundationJudgeContext.test.js b/server/services/pipeline/foundationJudgeContext.test.jsnew file mode 100644index 0000000000..6f096db0c9--- /dev/null+++ b/server/services/pipeline/foundationJudgeContext.test.js@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest';++import {+ foundationInputsHash,+ pickFrameworkFields,+ renderCharacterLine,+} from './foundationJudgeContext.js';++// The optional psychology profile (#6414) has to be invisible until an author+// actually writes one. Two things break loudly if it isn't: every existing+// install's foundation score is invalidated by a hash that gained an empty+// object, and every judge prompt grows a line of "unassessed" noise per cast+// member inside a budget this module works hard to hold.+describe('foundationJudgeContext — optional psychology profile (#6414)', () => {+ const legacyCharacter = {+ id: 'chr-1', name: 'Nera Vost', role: 'lead',+ ghost: 'Left behind on the Kesh run.', lie: 'I only matter if I win.',+ };+ const assessed = {+ ...legacyCharacter,+ psychology: {+ theoryOfControl: 'If I stay useful, nobody leaves.',+ strategy: "Absorbs everyone else's work.",+ protectiveBenefit: 'Never tests whether she would be kept anyway.',+ presentCost: 'A crew that never learns to carry itself.',+ drives: {+ survival: { desire: 'a berth she cannot be put out of', fear: 'being turned out' },+ connection: { desire: 'to be kept', fear: 'being easy to replace' },+ status: { desire: 'to be counted on', fear: 'being read as surplus' },+ },+ },+ };+ const series = { id: 'ser-1', name: 'Example Series', premise: 'A salvage crew.' };+ const universe = { id: 'uni-1', name: 'Example Universe', characters: [legacyCharacter] };++ it('leaves an unassessed character out of the projection and its hash', () => {+ expect(pickFrameworkFields(legacyCharacter)).not.toHaveProperty('psychology');+ // Byte-for-byte the same input hash as before the field existed, so an+ // upgrade does not invalidate a score nobody's data changed.+ expect(foundationInputsHash(series, universe))+ .toBe(foundationInputsHash(series, { ...universe, characters: [{ ...legacyCharacter }] }));+ });++ it('projects the profile — and moves the hash — once one is authored', () => {+ expect(pickFrameworkFields(assessed).psychology.drives.status.fear).toBe('being read as surplus');+ expect(foundationInputsHash(series, { ...universe, characters: [assessed] }))+ .not.toBe(foundationInputsHash(series, universe));+ });++ it('adds the control clause to the roster line only for an assessed character', () => {+ expect(renderCharacterLine(legacyCharacter)).not.toMatch(/control:/);+ const line = renderCharacterLine(assessed);+ expect(line).toMatch(/control: theory: If I stay useful, nobody leaves\./);+ expect(line).toMatch(/status desire: to be counted on, fear: being read as surplus/);+ });++ it('renders an explicit unknown ruling instead of an invented interior', () => {+ const line = renderCharacterLine({+ ...legacyCharacter,+ psychology: { assessment: 'not-applicable', assessmentNote: 'A swarm with no single interior.' },+ });+ expect(line).toMatch(/assessment: not-applicable \(A swarm with no single interior\.\)/);+ expect(line).toMatch(/theory: —/);+ });+});diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex cb7eba5975..e3c23f0ff2 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -41,7 +41,7 @@ import { findOrCreateUniverseCollection, findOrCreateSeriesCollection, addItem aimport { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';import { mergePeerAnnotations } from '../mediaAnnotations.js';-import { isStr, preserveLegacyCharacterProductionPackages } from '../../lib/storyBible.js';+import { isStr, preserveLegacyCharacterFields } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';import { maybeJournalBeforeOverwrite, flushBaseHashes, setSyncBaseHash, contentHashForRecord } from '../../lib/conflictJournal.js';@@ -566,7 +566,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =if (kind === 'universe') {record = {...record,- characters: preserveLegacyCharacterProductionPackages(+ characters: preserveLegacyCharacterFields(record.characters,existing.characters,senderUniversesVersion,diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 14871214f3..b2e8be6024 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -2323,7 +2323,7 @@ describe('sharing round-trip', () => {const exp = await exporter.exportSeries(s.id, bucket.id);const manifest = JSON.parse(readFileSync(join(tempBucket, 'manifests', exp.filename), 'utf-8'));expect(manifest.portosSchemaVersions).toBeDefined();- expect(manifest.portosSchemaVersions.universes).toBe(10);+ expect(manifest.portosSchemaVersions.universes).toBe(11);});it('preserves character production packages when an older peer wins universe LWW', async () => {diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex fb1867f475..9683ffb26b 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -3683,17 +3683,17 @@ describe('peerSync', () => {describe('receiver — applyIncomingPush', () => {it('rejects when sender schemaVersions.universes is AHEAD of local code', async () => {- // Local code is at universes:10 (see server/lib/schemaVersions.js).- // A push from a sender on universes:11 must NOT touch local state.+ // Local code is at universes:11 (see server/lib/schemaVersions.js).+ // A push from a sender on universes:12 must NOT touch local state.const rejection = await applyIncomingPush({kind: 'universe',record: { id: 'u1', name: 'Foo' },assetManifest: [],sourceInstanceId: 'peer-a',- portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 11 } },+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 12 } },}).catch((err) => err);expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');- expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 11, receiverV: 10 }]);+ expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 12, receiverV: 11 }]);expect(rejection.details.senderPortosVersion).toBe('99.0.0');// Receiver MUST stamp its OWN PortOS version so the sender can show// the user "peer X is on PortOS vY" — without this, the sender would@@ -3983,7 +3983,7 @@ describe('peerSync', () => {expect(call).toBeDefined();const body = JSON.parse(call[1].body);expect(body.portosMeta).toBeDefined();- expect(body.portosMeta.schemaVersions.universes).toBe(10);+ expect(body.portosMeta.schemaVersions.universes).toBe(11);expect(typeof body.portosMeta.portosVersion).toBe('string');});diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex cbf5acf503..6f25905f08 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -4,6 +4,7 @@ import { writeFile, mkdir } from "fs/promises";import { tmpdir } from "os";import { join } from "path";import { mockNoPeerSync, mockNoPeers } from "../lib/mockPathsDataRoot.js";+import { BIBLE_LIMITS } from "../lib/bibleLimits.js";// Real per-suite tmpdir backing the universes/ layout. Each test wipes the// tree in beforeEach. The fileUtils mock below overrides PATHS.data so the@@ -2996,4 +2997,167 @@ describe("universeBuilder service", () => {slot.clearPendingSheetSlotsForUniverse(u2.id);});});++ // ---------------------------------------------------------------------------+ // Character psychology profile (#6414)+ // ---------------------------------------------------------------------------+ //+ // The public boundary is create → getUniverse → updateUniverse, which is what+ // the Cast tab actually drives. These cases pin the contract that makes the+ // field safe to ship into installs that already hold characters: it is+ // absent until authored, it never rewrites the legacy framework fields, a+ // partial PATCH cannot wipe the leaves it omits, and an explicit clear works.+ describe("character psychology (#6414)", () => {+ const fullProfile = () => ({+ theoryOfControl: "If I stay useful, nobody leaves.",+ strategy: "Absorbs everyone else's work and never asks for anything back.",+ protectiveBenefit: "Keeps her from ever testing whether she'd be kept anyway.",+ presentCost: "Exhaustion, and a crew who never learns to carry its own weight.",+ testingPressure: "A job she physically cannot do alone.",+ candidateChange: "Asking for help before the failure, not after.",+ drives: {+ survival: { desire: "a berth she cannot be put out of", fear: "being turned out" },+ connection: { desire: "to be kept", fear: "being easy to replace" },+ status: { desire: "to be the one the crew counts on", fear: "being read as surplus" },+ },+ });++ it("round-trips a full profile through create → load → patch, and stays ABSENT until authored", async () => {+ const w = await svc.createUniverse({+ name: "Example Universe",+ characters: [+ { name: "Nera Vost", psychology: fullProfile() },+ { name: "Unassessed Sib" },+ ],+ });+ const loaded = await svc.getUniverse(w.id);+ const nera = loaded.characters.find((c) => c.name === "Nera Vost");+ const sib = loaded.characters.find((c) => c.name === "Unassessed Sib");++ expect(nera.psychology).toEqual({ ...fullProfile(), assessment: null, assessmentNote: "" });+ // A character nobody assessed carries no key at all — legacy records stay+ // byte-identical rather than gaining an empty husk that reads as filled.+ expect("psychology" in sib).toBe(false);++ const patched = await svc.updateUniverse(w.id, (cur) => ({+ characters: cur.characters.map((c) => (c.id === nera.id+ ? { ...c, psychology: { ...c.psychology, presentCost: "A crew that never grows up." } }+ : c)),+ }));+ const repatched = patched.characters.find((c) => c.id === nera.id);+ expect(repatched.psychology.presentCost).toBe("A crew that never grows up.");+ expect(repatched.psychology.theoryOfControl).toBe(fullProfile().theoryOfControl);+ expect(repatched.psychology.drives.status.fear).toBe("being read as surplus");+ });++ it("preserves an existing Lie verbatim when a psychology profile is added", async () => {+ const lie = "I only matter if I win.";+ const w = await svc.createUniverse({+ name: "Example Universe",+ characters: [{ name: "Nera Vost", lie, want: "the salvage contract", need: "to be kept anyway" }],+ });+ const [character] = w.characters;+ const patched = await svc.updateUniverse(w.id, (cur) => ({+ characters: cur.characters.map((c) => (c.id === character.id ? { ...c, psychology: fullProfile() } : c)),+ }));+ const next = patched.characters.find((c) => c.id === character.id);+ // The Lie is a judgment ABOUT a belief and the theory of control is the+ // operating rule — related, never the same statement, never overwritten.+ expect(next.lie).toBe(lie);+ expect(next.want).toBe("the salvage contract");+ expect(next.need).toBe("to be kept anyway");+ expect(next.psychology.theoryOfControl).toBe(fullProfile().theoryOfControl);+ expect(next.psychology.theoryOfControl).not.toBe(lie);+ });++ it("a PATCH that omits nested leaves clears only what it omitted — the caller sends the whole object", async () => {+ // The universe canon PATCH is a whole-list write, so a nested field is+ // replaced by the object the caller sends. That is exactly why the editor+ // spreads the persisted profile before committing; assert the contract so+ // a future caller that forgets is caught by a failing test, not by data+ // loss on a writer's machine.+ const w = await svc.createUniverse({+ name: "Example Universe",+ characters: [{ name: "Nera Vost", psychology: fullProfile() }],+ });+ const [character] = w.characters;+ const patched = await svc.updateUniverse(w.id, (cur) => ({+ characters: cur.characters.map((c) => (c.id === character.id+ ? { ...c, psychology: { theoryOfControl: "Only the work is safe." } }+ : c)),+ }));+ const next = patched.characters.find((c) => c.id === character.id);+ expect(next.psychology.theoryOfControl).toBe("Only the work is safe.");+ expect(next.psychology.strategy).toBe("");+ expect(next.psychology.drives.survival).toEqual({ desire: "", fear: "" });+ });++ it("clears the profile on an explicit null and on an all-blank object", async () => {+ const w = await svc.createUniverse({+ name: "Example Universe",+ characters: [+ { name: "Nera Vost", psychology: fullProfile() },+ { name: "Sole Ryn", psychology: fullProfile() },+ ],+ });+ const [nera, ryn] = w.characters;+ const patched = await svc.updateUniverse(w.id, (cur) => ({+ characters: cur.characters.map((c) => {+ if (c.id === nera.id) return { ...c, psychology: null };+ if (c.id === ryn.id) return { ...c, psychology: { theoryOfControl: " ", drives: {} } };+ return c;+ }),+ }));+ for (const id of [nera.id, ryn.id]) {+ const next = patched.characters.find((c) => c.id === id);+ expect("psychology" in next).toBe(false);+ }+ });++ it("records an explicit unknown / not-applicable ruling, and drops an unrecognized one", async () => {+ const w = await svc.createUniverse({+ name: "Example Universe",+ characters: [+ {+ name: "The Choir",+ psychology: {+ assessment: "not-applicable",+ assessmentNote: "A distributed swarm with no single interior to read a control theory from.",+ },+ },+ { name: "Bad Enum", psychology: { assessment: "definitely", theoryOfControl: "keep moving" } },+ ],+ });+ const choir = w.characters.find((c) => c.name === "The Choir");+ const badEnum = w.characters.find((c) => c.name === "Bad Enum");+ expect(choir.psychology.assessment).toBe("not-applicable");+ expect(choir.psychology.assessmentNote).toMatch(/distributed swarm/);+ expect(choir.psychology.theoryOfControl).toBe("");+ // An unrecognized ruling collapses to null rather than persisting a token+ // no consumer knows how to read — the rest of the profile survives.+ expect(badEnum.psychology.assessment).toBeNull();+ expect(badEnum.psychology.theoryOfControl).toBe("keep moving");+ });++ it("bounds every leaf and refuses a malformed nested shape", async () => {+ const w = await svc.createUniverse({+ name: "Example Universe",+ characters: [{+ name: "Nera Vost",+ psychology: {+ theoryOfControl: "x".repeat(BIBLE_LIMITS.THEORY_OF_CONTROL_MAX + 500),+ strategy: 42,+ drives: [{ desire: "not an object map" }],+ },+ }],+ });+ const [character] = w.characters;+ expect(character.psychology.theoryOfControl).toHaveLength(BIBLE_LIMITS.THEORY_OF_CONTROL_MAX);+ expect(character.psychology.strategy).toBe("");+ // A non-object `drives` still materializes the three empty axes rather+ // than persisting an array a reader would index by number.+ expect(Object.keys(character.psychology.drives)).toEqual(["survival", "connection", "status"]);+ expect(character.psychology.drives.connection).toEqual({ desire: "", fear: "" });+ });+ });});diff --git a/server/services/universeBuilder/sync.js b/server/services/universeBuilder/sync.jsindex be3cbc1939..955b159621 100644--- a/server/services/universeBuilder/sync.js+++ b/server/services/universeBuilder/sync.js@@ -8,7 +8,7 @@* re-exports this module so existing import paths keep working.*/-import { isStr, preserveLegacyCharacterProductionPackages } from '../../lib/storyBible.js';+import { isStr, preserveLegacyCharacterFields } from '../../lib/storyBible.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,deleteSyncBaseHash, withBaseHashFlushBatch,@@ -150,7 +150,7 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:if (!sanitized.moodBoardId && local.moodBoardId && !senderKnowsMoodBoardId) {sanitized.moodBoardId = local.moodBoardId;}- sanitized.characters = preserveLegacyCharacterProductionPackages(+ sanitized.characters = preserveLegacyCharacterFields(sanitized.characters,local.characters,senderUniversesVersion,diff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.jsindex 5c2275a4c9..5b8f70fb20 100644--- a/server/services/universeCharacterExpand.js+++ b/server/services/universeCharacterExpand.js@@ -13,7 +13,7 @@import { buildStyleClause } from './universeCanon.js';import { runCanonEntryExpand } from './universeCanonExpandRunner.js';-import { BIBLE_KIND, sanitizeBibleField } from '../lib/storyBible.js';+import { BIBLE_KIND, sanitizeBibleField, PSYCHOLOGY_DRIVE_AXES } from '../lib/storyBible.js';import { BIBLE_EXPAND_FIELDS, bibleFieldIsBlank, SLIDER_AXES } from '../lib/universeBibleCompleteness.js';// Adding a new extended field on `sanitizeCharacter` requires adding it to@@ -42,6 +42,13 @@ const peerForExpandPrompt = (entry) => ({coreTheme: entry.coreTheme || '',});+// The flat prose leaves of the psychology profile. `drives` and `assessment`+// are merged separately below (nested object / author ruling).+const PSYCHOLOGY_STRING_FIELDS = Object.freeze([+ 'theoryOfControl', 'strategy', 'protectiveBenefit', 'presentCost',+ 'testingPressure', 'candidateChange', 'assessmentNote',+]);+const isAbsent = (v) => v === undefined || v === null;// Exported so the vision-expand path can compute the same "which fields are// still blank" set it narrows the LLM ask to.@@ -113,6 +120,47 @@ export function applyExpansion(target, content) {updatedFields.push('sliders');}}+ // psychology (#6414) — a nested profile merged LEAF by leaf, not wholesale.+ // A partial proposal must never replace a populated leaf, and must never+ // drop the leaves the author already wrote (which is what assigning the+ // sanitized proposal directly would do). Same fill-blanks-only contract as+ // the sliders above, one level deeper.+ if (content.psychology && typeof content.psychology === 'object' && !Array.isArray(content.psychology)) {+ const proposed = sanitizeBibleField('character', target, 'psychology', content.psychology);+ if (proposed) {+ const existing = (target.psychology && typeof target.psychology === 'object' && !Array.isArray(target.psychology))+ ? target.psychology+ : {};+ const next = { ...existing };+ let changed = false;+ for (const field of PSYCHOLOGY_STRING_FIELDS) {+ if (!isBlankString(existing[field]) || isBlankString(proposed[field])) continue;+ next[field] = proposed[field];+ changed = true;+ }+ // An `assessment` ruling is the author's call; only fill it when unset.+ if (!existing.assessment && proposed.assessment) {+ next.assessment = proposed.assessment;+ changed = true;+ }+ const nextDrives = { ...(existing.drives && typeof existing.drives === 'object' ? existing.drives : {}) };+ for (const axis of PSYCHOLOGY_DRIVE_AXES) {+ const existingAxis = nextDrives[axis] && typeof nextDrives[axis] === 'object' ? nextDrives[axis] : {};+ const proposedAxis = proposed.drives?.[axis] || {};+ const mergedAxis = { ...existingAxis };+ for (const leaf of ['desire', 'fear']) {+ if (!isBlankString(existingAxis[leaf]) || isBlankString(proposedAxis[leaf])) continue;+ mergedAxis[leaf] = proposedAxis[leaf];+ changed = true;+ }+ nextDrives[axis] = mergedAxis;+ }+ if (changed) {+ merged.psychology = { ...next, drives: nextDrives };+ updatedFields.push('psychology');+ }+ }+ }return { merged, updatedFields };}diff --git a/server/services/universeCharacterExpand.test.js b/server/services/universeCharacterExpand.test.jsindex dd34345ba5..f416a3eb43 100644--- a/server/services/universeCharacterExpand.test.js+++ b/server/services/universeCharacterExpand.test.js@@ -244,3 +244,79 @@ describe('universeCharacterExpand — applyExpansion (no-clobber merge semanticsexpect(merged.pronouns).toBe('');});});++describe('universeCharacterExpand — psychology profile merge (#6414)', () => {+ const proposal = () => ({+ psychology: {+ theoryOfControl: 'If I stay useful, nobody leaves.',+ strategy: "Absorbs everyone else's work.",+ protectiveBenefit: 'Never has to test whether she would be kept anyway.',+ presentCost: 'Exhaustion.',+ drives: {+ survival: { desire: 'a berth she cannot be put out of', fear: 'being turned out' },+ connection: { desire: 'to be kept', fear: 'being easy to replace' },+ status: { desire: 'to be counted on', fear: 'being read as surplus' },+ },+ },+ });++ it('authors a whole profile on a character that has none', () => {+ const { merged, updatedFields } = applyExpansion({ name: 'Nera' }, proposal());+ expect(updatedFields).toContain('psychology');+ expect(merged.psychology.theoryOfControl).toBe('If I stay useful, nobody leaves.');+ expect(merged.psychology.drives.status.fear).toBe('being read as surplus');+ });++ it('fills only the blank leaves of a partly-authored profile', () => {+ const target = {+ name: 'Nera',+ psychology: {+ theoryOfControl: 'Only the work is safe.',+ strategy: '',+ drives: {+ survival: { desire: 'her own berth', fear: '' },+ connection: { desire: '', fear: '' },+ status: { desire: '', fear: '' },+ },+ },+ };+ const { merged, updatedFields } = applyExpansion(target, proposal());+ expect(updatedFields).toContain('psychology');+ // Authored leaves survive verbatim…+ expect(merged.psychology.theoryOfControl).toBe('Only the work is safe.');+ expect(merged.psychology.drives.survival.desire).toBe('her own berth');+ // …blank ones fill, including one blank leaf inside a partly-filled axis.+ expect(merged.psychology.strategy).toBe("Absorbs everyone else's work.");+ expect(merged.psychology.drives.survival.fear).toBe('being turned out');+ expect(merged.psychology.drives.connection.desire).toBe('to be kept');+ });++ it('reports no update when every proposed leaf is already authored', () => {+ const target = { name: 'Nera', psychology: proposal().psychology };+ const { merged, updatedFields } = applyExpansion(target, proposal());+ expect(updatedFields).not.toContain('psychology');+ expect(merged.psychology).toBe(target.psychology);+ });++ it('never proposes an assessment ruling over one the author already made', () => {+ const target = {+ name: 'The Choir',+ psychology: { assessment: 'not-applicable', assessmentNote: 'A swarm with no single interior.' },+ };+ const { merged } = applyExpansion(target, {+ psychology: { assessment: 'assessed', theoryOfControl: 'Consensus keeps the body alive.' },+ });+ expect(merged.psychology.assessment).toBe('not-applicable');+ expect(merged.psychology.assessmentNote).toBe('A swarm with no single interior.');+ // The blank prose leaf still fills — the ruling is what is protected.+ expect(merged.psychology.theoryOfControl).toBe('Consensus keeps the body alive.');+ });++ it('ignores an empty or malformed proposal rather than stamping an empty husk', () => {+ for (const psychology of [{}, { drives: {} }, [], 'nope', { theoryOfControl: ' ' }]) {+ const { merged, updatedFields } = applyExpansion({ name: 'Nera' }, { psychology });+ expect(updatedFields).not.toContain('psychology');+ expect(merged.psychology).toBeUndefined();+ }+ });+});diff --git a/server/services/universeVisionExpand.js b/server/services/universeVisionExpand.jsindex 15be3f4c16..692dfc8ef2 100644--- a/server/services/universeVisionExpand.js+++ b/server/services/universeVisionExpand.js@@ -60,6 +60,14 @@ const LIST_FIELD_SHAPES = {// are already absent from both shared lists (merged specially in the text flow),// so they never reach the vision prompt either.const NON_VISUAL_FRAMEWORK_FIELDS = new Set(['ghost', 'wound', 'lie', 'want', 'need', 'secrets']);+// The structured psychology profile (#6414) is the same kind of material one+// level deeper — a theory of control and its survival/connection/status drives+// are an interior, not a rendered surface. It never reaches the prompt (it is+// an `objects` field, so it is in neither shared list), but the shared+// `applyExpansion` WOULD merge it, so a model that volunteers the key anyway+// must not be able to author a character's psychology from a picture. Stripped+// from the payload before the merge rather than trusted to the prompt.+const NON_VISUAL_PROPOSAL_KEYS = Object.freeze(['psychology']);/*** Build the vision prompt. The model is told to return ONE JSON object keyed by@@ -202,6 +210,7 @@ export async function expandEntityFromImages({// fills only blank fields and sanitizes list rows. Surface just the fields it// would fill (name → merged value) so the modal can present them for review;// the client applies the kept/edited values via the normal entry-PATCH path.+ for (const key of NON_VISUAL_PROPOSAL_KEYS) delete content[key];const { merged, updatedFields } = applyExpansion(target, content);const fields = {};for (const f of updatedFields) fields[f] = merged[f];diff --git a/server/services/universeVisionExpand.test.js b/server/services/universeVisionExpand.test.jsindex 76a6853427..e0e93d2ea1 100644--- a/server/services/universeVisionExpand.test.js+++ b/server/services/universeVisionExpand.test.js@@ -176,3 +176,29 @@ describe('expandEntityFromImages', () => {.rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });});});++describe('universeVisionExpand — psychology is never authored from a picture (#6414)', () => {+ it('drops a volunteered psychology profile instead of merging it', async () => {+ promptRunner.runPromptThroughProvider.mockResolvedValue({+ text: JSON.stringify({+ pronouns: 'she/her',+ psychology: {+ theoryOfControl: 'If I stay armored, nothing reaches me.',+ drives: { survival: { desire: 'cover', fear: 'exposure' } },+ },+ }),+ model: 'qwen-vl',+ });+ const out = await expandEntityFromImages({ universeId: 'uni-1', entryId: 'chr-1', screenshots: ['a.png'] });+ // The visible field still fills; the interior does not.+ expect(out.fields.pronouns).toBe('she/her');+ expect(out.fields).not.toHaveProperty('psychology');+ expect(out.updatedFields).not.toContain('psychology');+ });++ it('never asks a vision model for the profile in the first place', () => {+ const full = buildVisionExpandPrompt({ imageCount: 1 });+ expect(full).not.toMatch(/"psychology"/);+ expect(full).not.toMatch(/theoryOfControl/);+ });+});