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([issue-708]): persona trait-blending rules for per-context voice calibration
[._.]/ Adam Eivy8322a8dd891f
diff --git a/client/src/components/digital-twin/tabs/PersonasTab.jsx b/client/src/components/digital-twin/tabs/PersonasTab.jsxindex f931ce2fc0..889bebdcb0 100644--- a/client/src/components/digital-twin/tabs/PersonasTab.jsx+++ b/client/src/components/digital-twin/tabs/PersonasTab.jsx@@ -1,10 +1,46 @@import { useState, useEffect } from 'react';-import { Drama, Plus, Pencil, Trash2, Check, X, CheckCircle2 } from 'lucide-react';+import { Drama, Plus, Pencil, Trash2, Check, X, CheckCircle2, SlidersHorizontal } from 'lucide-react';import BrailleSpinner from '../../BrailleSpinner';import * as api from '../../../services/api';import toast from '../../ui/Toast';+import { describeTraitAdjustments, BIG_FIVE_LEAN } from '../../../lib/personaTraitBlend.js';-const EMPTY_FORM = { name: '', description: '', instructions: '' };+const EMOJI_OPTIONS = ['never', 'rare', 'occasional', 'frequent'];+const BIG_FIVE_KEYS = ['O', 'C', 'E', 'A', 'N'];+const BIG_FIVE_LABELS = { O: 'Openness', C: 'Conscientiousness', E: 'Extraversion', A: 'Agreeableness', N: 'Neuroticism' };++// The editor's working shape. '' / 0 mean "no override" for that field; the+// payload builder strips them so an untouched editor sends no traitAdjustments.+const EMPTY_ADJUSTMENTS = { formality: 0, verbosity: 0, emojiUsage: '', tone: '', bigFive: { O: 0, C: 0, E: 0, A: 0, N: 0 } };+const EMPTY_FORM = { name: '', description: '', instructions: '', adjustments: EMPTY_ADJUSTMENTS };++// Hydrate the editor shape from a stored persona's traitAdjustments.+function adjustmentsToForm(traitAdjustments) {+ const a = traitAdjustments || {};+ return {+ formality: a.formality ?? 0,+ verbosity: a.verbosity ?? 0,+ emojiUsage: a.emojiUsage ?? '',+ tone: a.tone ?? '',+ bigFive: BIG_FIVE_KEYS.reduce((acc, k) => ({ ...acc, [k]: a.bigFive?.[k] ?? 0 }), {})+ };+}++// Build the API payload from the editor shape, dropping no-op fields. Returns+// null when nothing is set so callers can clear adjustments to instructions-only.+function buildAdjustmentsPayload(adj) {+ const out = {};+ if (adj.formality) out.formality = adj.formality;+ if (adj.verbosity) out.verbosity = adj.verbosity;+ if (adj.emojiUsage) out.emojiUsage = adj.emojiUsage;+ if (adj.tone?.trim()) out.tone = adj.tone.trim();+ const bigFive = BIG_FIVE_KEYS.reduce((acc, k) => {+ if (adj.bigFive?.[k]) acc[k] = adj.bigFive[k];+ return acc;+ }, {});+ if (Object.keys(bigFive).length > 0) out.bigFive = bigFive;+ return Object.keys(out).length > 0 ? out : null;+}/*** Twin Personas (M34 P7). Named context variants whose instructions are@@ -46,10 +82,12 @@ export default function PersonasTab({ onRefresh }) {return;}setBusy(true);+ const traitAdjustments = buildAdjustmentsPayload(createForm.adjustments);const persona = await api.createDigitalTwinPersona({name: createForm.name.trim(),description: createForm.description.trim() || undefined,- instructions: createForm.instructions.trim()+ instructions: createForm.instructions.trim(),+ ...(traitAdjustments ? { traitAdjustments } : {})}).catch(() => null);setBusy(false);if (!persona) return;@@ -65,7 +103,8 @@ export default function PersonasTab({ onRefresh }) {setEditForm({name: persona.name,description: persona.description || '',- instructions: persona.instructions+ instructions: persona.instructions,+ adjustments: adjustmentsToForm(persona.traitAdjustments)});};@@ -75,10 +114,13 @@ export default function PersonasTab({ onRefresh }) {return;}setBusy(true);+ // null clears adjustments back to an instructions-only persona; an object replaces them.+ const traitAdjustments = buildAdjustmentsPayload(editForm.adjustments);const updated = await api.updateDigitalTwinPersona(id, {name: editForm.name.trim(),description: editForm.description.trim(),- instructions: editForm.instructions.trim()+ instructions: editForm.instructions.trim(),+ traitAdjustments}).catch(() => null);setBusy(false);if (!updated) return;@@ -247,6 +289,17 @@ export default function PersonasTab({ onRefresh }) {</div><p className="text-sm text-gray-300 mt-3 whitespace-pre-wrap bg-port-bg p-3 rounded">{persona.instructions}</p>+ {describeTraitAdjustments(persona.traitAdjustments).length > 0 && (+ <div className="mt-3 flex items-center gap-2 flex-wrap">+ <span className="flex items-center gap-1 text-xs text-gray-500">+ <SlidersHorizontal className="w-3.5 h-3.5" /> Voice:+ </span>+ {describeTraitAdjustments(persona.traitAdjustments).map((d, i) => (+ <span key={i} className="text-xs px-2 py-0.5 rounded bg-port-bg border border-port-border text-gray-300">{d}</span>+ ))}+ </div>+ )}+{confirmDeleteId === persona.id && (<div className="flex items-center justify-between gap-3 mt-3 p-3 rounded bg-port-error/10 border border-port-error/30"><span className="text-sm text-port-error">Delete "{persona.name}"?</span>@@ -317,6 +370,175 @@ function PersonaForm({ form, setForm, idPrefix }) {className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none resize-y"/></div>+ <TraitAdjustmentsEditor+ idPrefix={idPrefix}+ adjustments={form.adjustments}+ setAdjustments={(updater) => setForm(f => ({ ...f, adjustments: updater(f.adjustments) }))}+ />+ </div>+ );+}++/**+ * Trait-blending editor (M34 P7). Lets a persona modulate the base twin's+ * quantitative voice for its context: relative formality/verbosity sliders,+ * an emoji override, a tone phrase, and directional Big-Five leans. A live+ * preview renders the same wording the embodied twin will see, via the shared+ * `describeTraitAdjustments` helper. Collapsed by default for instructions-only+ * personas; opens automatically when any adjustment is already set.+ */+function TraitAdjustmentsEditor({ idPrefix, adjustments, setAdjustments }) {+ const preview = describeTraitAdjustments(buildAdjustmentsPayload(adjustments) || {});+ const [open, setOpen] = useState(preview.length > 0);++ const setField = (key, value) => setAdjustments(a => ({ ...a, [key]: value }));+ const setBigFive = (key, value) => setAdjustments(a => ({ ...a, bigFive: { ...a.bigFive, [key]: value } }));+ const reset = () => setAdjustments(() => ({ ...EMPTY_ADJUSTMENTS, bigFive: { ...EMPTY_ADJUSTMENTS.bigFive } }));++ return (+ <div className="border border-port-border rounded-lg">+ <button+ type="button"+ onClick={() => setOpen(o => !o)}+ className="w-full flex items-center justify-between gap-2 px-3 py-2.5 min-h-[44px] text-left text-sm text-gray-300 hover:text-white"+ aria-expanded={open}+ >+ <span className="flex items-center gap-2">+ <SlidersHorizontal className="w-4 h-4 text-port-accent" />+ Voice calibration <span className="text-gray-600">(optional)</span>+ </span>+ <span className="text-xs text-gray-500">{open ? 'Hide' : preview.length > 0 ? `${preview.length} set` : 'Add'}</span>+ </button>++ {open && (+ <div className="px-3 pb-3 space-y-4 border-t border-port-border pt-3">+ <p className="text-xs text-gray-500">+ Nudge how your twin communicates in this context, relative to your base profile. Leave a slider at center for no change.+ </p>++ <SliderRow+ id={`${idPrefix}-formality`}+ label="Formality"+ hint={adjustments.formality > 0 ? 'more formal' : adjustments.formality < 0 ? 'more casual' : 'no change'}+ value={adjustments.formality}+ onChange={(v) => setField('formality', v)}+ />+ <SliderRow+ id={`${idPrefix}-verbosity`}+ label="Verbosity"+ hint={adjustments.verbosity > 0 ? 'more elaborate' : adjustments.verbosity < 0 ? 'more concise' : 'no change'}+ value={adjustments.verbosity}+ onChange={(v) => setField('verbosity', v)}+ />++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label htmlFor={`${idPrefix}-emoji`} className="block text-sm text-gray-400 mb-1">Emoji usage</label>+ <select+ id={`${idPrefix}-emoji`}+ value={adjustments.emojiUsage}+ onChange={(e) => setField('emojiUsage', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"+ >+ <option value="">No override</option>+ {EMOJI_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor={`${idPrefix}-tone`} className="block text-sm text-gray-400 mb-1">Tone</label>+ <input+ id={`${idPrefix}-tone`}+ type="text"+ value={adjustments.tone}+ onChange={(e) => setField('tone', e.target.value)}+ placeholder="e.g. warm, crisp, playful"+ maxLength={100}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ </div>++ <div>+ <span className="block text-sm text-gray-400 mb-1">Personality lean</span>+ <div className="space-y-2">+ {BIG_FIVE_KEYS.map(k => (+ <BigFiveRow+ key={k}+ id={`${idPrefix}-bigfive-${k}`}+ label={BIG_FIVE_LABELS[k]}+ more={BIG_FIVE_LEAN[k].more}+ less={BIG_FIVE_LEAN[k].less}+ value={adjustments.bigFive[k]}+ onChange={(v) => setBigFive(k, v)}+ />+ ))}+ </div>+ </div>++ <div className="flex items-center justify-between gap-3 pt-1">+ <div className="text-xs text-gray-400 min-w-0">+ {preview.length > 0 ? (+ <span><span className="text-gray-500">Preview:</span> {preview.join(' · ')}</span>+ ) : (+ <span className="text-gray-600">No calibration set — this persona uses instructions only.</span>+ )}+ </div>+ {preview.length > 0 && (+ <button type="button" onClick={reset} className="text-xs text-gray-500 hover:text-port-error shrink-0">Clear</button>+ )}+ </div>+ </div>+ )}+ </div>+ );+}++// A -9..+9 relative slider centered on 0 (no change).+function SliderRow({ id, label, hint, value, onChange }) {+ return (+ <div>+ <div className="flex items-center justify-between mb-1">+ <label htmlFor={id} className="text-sm text-gray-400">{label}</label>+ <span className="text-xs text-gray-500">{hint}</span>+ </div>+ <input+ id={id}+ type="range"+ min={-9}+ max={9}+ step={1}+ value={value}+ onChange={(e) => onChange(Number(e.target.value))}+ className="w-full accent-port-accent"+ />+ </div>+ );+}++// Round a 0.1-step slider value to one decimal so float noise (0.1*3 = 0.30000…4)+// never reaches the persisted payload.+const roundTenth = (n) => Math.round(n * 10) / 10;++// A -1..+1 Big-Five lean slider (step 0.1), labeled with its directional poles.+function BigFiveRow({ id, label, more, less, value, onChange }) {+ return (+ <div>+ <div className="flex items-center justify-between mb-1 gap-2">+ <label htmlFor={id} className="text-sm text-gray-400 shrink-0">{label}</label>+ <span className="text-xs text-gray-500 truncate">+ {value > 0 ? more : value < 0 ? less : 'no change'}+ </span>+ </div>+ <input+ id={id}+ type="range"+ min={-1}+ max={1}+ step={0.1}+ value={value}+ onChange={(e) => onChange(roundTenth(Number(e.target.value)))}+ className="w-full accent-port-accent"+ /></div>);}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex e6663faca6..1aa428a87b 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -27,6 +27,7 @@ grep -i "what you want to do" client/src/lib/README.md| `scenePrompt.js` | Mirror of `server/lib/scenePrompt.js`. Scene-prompt composer + bible matchers. || `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. `composeCanonStyledPrompt` builds the `"<name>: <description>"` + universe-preset render the canon section and characters step share. || `cleanPlatePrompt.js` | Clean-plate prompt builder for setting canon entries (Cluster A — A4). |+| `personaTraitBlend.js` | Mirror of `server/lib/personaTraitBlend.js`. Digital-twin persona trait-blending (M34 P7) — `describeTraitAdjustments` / `renderTraitBlendDirective` / `BIG_FIVE_LEAN` for the Personas UI preview. || `seasonStructure.js` | Mirror of `server/lib/seasonStructure.js`. || `sheetPointers.js` | Mirror of the character-sheet pointer helpers from `server/lib/storyBible.js`. `LEGACY_SHEET_VARIANT_ID` + `readSheetPointer` / `listSheetPointers` / `applySheetPointer` for traversing both the legacy `referenceSheetImageRef` field and the `referenceSheets` map. || `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 8720d9921d..9af66f9c18 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -6,6 +6,7 @@export * from './canonPrompt.js';export * from './cleanPlatePrompt.js';export * from './composeStyledPrompt.js';+export * from './personaTraitBlend.js';export * from './scenePrompt.js';export * from './seasonStructure.js';export * from './sheetPointers.js';diff --git a/client/src/lib/personaTraitBlend.js b/client/src/lib/personaTraitBlend.jsnew file mode 100644index 0000000000..a3e5d2d9a3--- /dev/null+++ b/client/src/lib/personaTraitBlend.js@@ -0,0 +1,223 @@+/**+ * Persona trait-blending (Digital Twin M34 P7).+ *+ * A persona is a named context (Professional, Casual, Family…). Beyond its+ * free-text `instructions`, a persona may carry structured `traitAdjustments`+ * that modulate the *base* twin's quantitative profile for that context —+ * relative nudges to the communication profile (formality / verbosity) plus+ * absolute overrides (emoji usage, tone) and directional Big-Five leans.+ *+ * This module blends those adjustments against the base twin's `traits` and+ * renders a "Communication Calibration" directive that prepends to the persona+ * preamble (see `digital-twin-context.js`), so the embodied twin shifts voice+ * per context without forking the underlying identity documents.+ *+ * Pure ESM, no Node-only deps — mirrored byte-for-byte to+ * `client/src/lib/personaTraitBlend.js` so the Personas UI can preview the same+ * directional wording. The server copy is authoritative; the matching server+ * test file (`personaTraitBlend.test.js`) is the contract.+ */++// communicationProfile.formality / .verbosity live on a 1..10 scale; a persona+// nudges them with a relative integer delta in this range.+export const COMM_DELTA_MIN = -9;+export const COMM_DELTA_MAX = 9;++// Big-Five (OCEAN) base traits live on a 0..1 scale; a persona leans them with+// a relative delta in this range.+export const BIG_FIVE_DELTA_MIN = -1;+export const BIG_FIVE_DELTA_MAX = 1;++export const BIG_FIVE_LEAN = {+ O: { more: 'more open and curious', less: 'more conventional and focused' },+ C: { more: 'more conscientious and organized', less: 'more relaxed and spontaneous' },+ E: { more: 'more outgoing and expressive', less: 'more reserved and measured' },+ A: { more: 'warmer and more accommodating', less: 'more direct and challenging' },+ N: { more: 'more emotionally expressive', less: 'more even-keeled and calm' }+};++const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));++// Bare magnitude adverb for a 1..10-scale delta (slightly / notably / much) —+// used where the paired verb already encodes direction (e.g. "more concise").+function commAdverb(delta) {+ const mag = Math.abs(delta);+ if (mag >= 5) return 'much';+ if (mag >= 3) return 'notably';+ return 'slightly';+}++// Signed wording for a fixed-quality 1..10 trait (e.g. formality): the quality+// word stays put and direction is "more"/"less" of it — "much more formal".+function commMagnitude(delta) {+ return `${commAdverb(delta)} ${delta > 0 ? 'more' : 'less'}`;+}++// Verbosity flips its quality word with sign — negative = more concise,+// positive = more elaborate — so it always reads "{adverb} more {quality}".+function verbosityPhrase(delta) {+ return `${commAdverb(delta)} more ${delta > 0 ? 'elaborate' : 'concise'}`;+}++// Magnitude wording for a 0..1-scale Big-Five delta.+function bigFiveMagnitude(delta) {+ const mag = Math.abs(delta);+ if (mag >= 0.4) return 'much';+ if (mag >= 0.2) return 'notably';+ return 'slightly';+}++/**+ * Does this persona carry any structured trait adjustment worth rendering?+ * Empty objects / all-absent fields count as "none".+ */+export function hasTraitAdjustments(adjustments) {+ if (!adjustments || typeof adjustments !== 'object') return false;+ const { formality, verbosity, emojiUsage, tone, bigFive } = adjustments;+ if (typeof formality === 'number' && formality !== 0) return true;+ if (typeof verbosity === 'number' && verbosity !== 0) return true;+ if (typeof emojiUsage === 'string' && emojiUsage) return true;+ if (typeof tone === 'string' && tone.trim()) return true;+ if (bigFive && typeof bigFive === 'object') {+ return Object.keys(BIG_FIVE_LEAN).some(k => typeof bigFive[k] === 'number' && bigFive[k] !== 0);+ }+ return false;+}++/**+ * Blend a persona's adjustments against the base communication profile,+ * returning the effective values plus the base for "X → Y" rendering. Missing+ * base values surface as `null` so callers can render a directional-only line.+ */+export function blendCommunicationProfile(baseProfile, adjustments) {+ const base = baseProfile && typeof baseProfile === 'object' ? baseProfile : {};+ const adj = adjustments && typeof adjustments === 'object' ? adjustments : {};++ const blendScale = (baseVal, delta) => {+ const hasBase = typeof baseVal === 'number';+ const hasDelta = typeof delta === 'number' && delta !== 0;+ if (!hasDelta) return { base: hasBase ? baseVal : null, effective: hasBase ? baseVal : null, delta: 0 };+ return {+ base: hasBase ? baseVal : null,+ effective: hasBase ? clamp(baseVal + delta, 1, 10) : null,+ delta+ };+ };++ return {+ formality: blendScale(base.formality, adj.formality),+ verbosity: blendScale(base.verbosity, adj.verbosity),+ emojiUsage: typeof adj.emojiUsage === 'string' && adj.emojiUsage+ ? { base: base.emojiUsage ?? null, effective: adj.emojiUsage }+ : null,+ tone: typeof adj.tone === 'string' && adj.tone.trim()+ ? { base: base.preferredTone ?? null, effective: adj.tone.trim() }+ : null+ };+}++/**+ * Human-readable, base-agnostic descriptions of each adjustment — used by the+ * Personas UI preview where the base profile isn't loaded. One short phrase per+ * active adjustment; empty array when there's nothing to say.+ */+export function describeTraitAdjustments(adjustments) {+ if (!hasTraitAdjustments(adjustments)) return [];+ const adj = adjustments;+ const lines = [];++ if (typeof adj.formality === 'number' && adj.formality !== 0) {+ lines.push(`${commMagnitude(adj.formality)} formal`);+ }+ if (typeof adj.verbosity === 'number' && adj.verbosity !== 0) {+ lines.push(verbosityPhrase(adj.verbosity));+ }+ if (typeof adj.emojiUsage === 'string' && adj.emojiUsage) {+ lines.push(`emoji usage: ${adj.emojiUsage}`);+ }+ if (typeof adj.tone === 'string' && adj.tone.trim()) {+ lines.push(`tone: ${adj.tone.trim()}`);+ }+ if (adj.bigFive && typeof adj.bigFive === 'object') {+ for (const k of Object.keys(BIG_FIVE_LEAN)) {+ const d = adj.bigFive[k];+ if (typeof d === 'number' && d !== 0) {+ const lean = d > 0 ? BIG_FIVE_LEAN[k].more : BIG_FIVE_LEAN[k].less;+ lines.push(`${bigFiveMagnitude(d)} ${lean}`);+ }+ }+ }+ return lines;+}++/**+ * Render the "Communication Calibration" directive block that prepends to a+ * persona's preamble. Blends `adjustments` against the base twin's `traits`+ * (communicationProfile + bigFive). Returns '' when the persona has no+ * adjustments so the preamble stays unchanged for instructions-only personas.+ */+export function renderTraitBlendDirective(baseTraits, adjustments, personaName = '') {+ if (!hasTraitAdjustments(adjustments)) return '';++ const traits = baseTraits && typeof baseTraits === 'object' ? baseTraits : {};+ const blended = blendCommunicationProfile(traits.communicationProfile, adjustments);+ const lines = [];++ // `phrase(delta)` returns the full directional description for this scale's+ // delta (e.g. "notably more formal" / "much more concise").+ const renderScale = (label, slot, phrase) => {+ if (!slot || slot.delta === 0) return;+ const text = phrase(slot.delta);+ if (slot.base !== null && slot.effective !== null) {+ lines.push(`- ${label}: ${slot.base} → ${slot.effective} (${text})`);+ } else {+ // No baseline recorded — render the directional intent relative to default.+ lines.push(`- ${label}: ${text} than your natural default`);+ }+ };++ renderScale('Formality', blended.formality, (d) => `${commMagnitude(d)} formal`);+ renderScale('Verbosity', blended.verbosity, verbosityPhrase);++ if (blended.emojiUsage) {+ const from = blended.emojiUsage.base ? ` (baseline ${blended.emojiUsage.base})` : '';+ lines.push(`- Emoji usage: ${blended.emojiUsage.effective}${from}`);+ }+ if (blended.tone) {+ const from = blended.tone.base ? ` (baseline ${blended.tone.base})` : '';+ lines.push(`- Tone: ${blended.tone.effective}${from}`);+ }++ // Big-Five leans, rendered as directional personality nudges.+ const adjBigFive = adjustments.bigFive && typeof adjustments.bigFive === 'object' ? adjustments.bigFive : {};+ const baseBigFive = traits.bigFive && typeof traits.bigFive === 'object' ? traits.bigFive : {};+ const leanLines = [];+ for (const k of Object.keys(BIG_FIVE_LEAN)) {+ const d = adjBigFive[k];+ if (typeof d !== 'number' || d === 0) continue;+ const lean = d > 0 ? BIG_FIVE_LEAN[k].more : BIG_FIVE_LEAN[k].less;+ const baseVal = typeof baseBigFive[k] === 'number' ? baseBigFive[k] : null;+ if (baseVal !== null) {+ const eff = clamp(baseVal + d, 0, 1);+ leanLines.push(`${bigFiveMagnitude(d)} ${lean} (${baseVal.toFixed(2)} → ${eff.toFixed(2)})`);+ } else {+ leanLines.push(`${bigFiveMagnitude(d)} ${lean}`);+ }+ }+ if (leanLines.length > 0) {+ lines.push(`- Personality lean: ${leanLines.join('; ')}`);+ }++ if (lines.length === 0) return '';++ const heading = personaName+ ? `## Communication Calibration (${personaName} context)`+ : '## Communication Calibration';++ return [+ heading,+ 'Modulate your baseline communication for this context:',+ ...lines,+ 'Where a baseline value is unknown, apply the directional adjustment relative to your natural default.'+ ].join('\n');+}diff --git a/server/lib/README.md b/server/lib/README.mdindex 522a4a5ce4..a6d9edc418 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -173,6 +173,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `issueLength.js` | Per-issue size targets fed into text stages. || `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. || `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |+| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. Mirrored to `client/src/lib/`. || `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. || `planIds.js` | Utilities for PLAN.md `[slug]` IDs. || `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex ff817d782b..07d51f122a 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -150,6 +150,28 @@ export const soulSettingsSchema = digitalTwinSettingsSchema; // Alias for backwa// --- Phase 7: Twin Personas (M34 P7) ---+// Trait-blending rules (M34 P7). Beyond free-text instructions, a persona may+// modulate the *base* twin's quantitative profile for its context: relative+// nudges to formality/verbosity (the 1..10 communicationProfile scale, so a+// ±9 delta can reach either end), absolute overrides for emoji usage and tone,+// and directional Big-Five leans (0..1 scale → ±1 delta). All fields optional;+// an instructions-only persona omits the whole object. The blend + directive+// rendering live in `server/lib/personaTraitBlend.js`.+const bigFiveDelta = z.number().min(-1).max(1);+export const personaTraitAdjustmentsSchema = z.object({+ formality: z.number().int().min(-9).max(9).optional(),+ verbosity: z.number().int().min(-9).max(9).optional(),+ emojiUsage: z.enum(['never', 'rare', 'occasional', 'frequent']).optional(),+ tone: z.string().max(100).optional(),+ bigFive: z.object({+ O: bigFiveDelta.optional(),+ C: bigFiveDelta.optional(),+ E: bigFiveDelta.optional(),+ A: bigFiveDelta.optional(),+ N: bigFiveDelta.optional()+ }).optional()+});+// A persona is a named context variant. Its instructions are prepended to the// twin context so the embodied twin modulates voice/behavior for a context// (Professional, Casual, Family, …) without forking the underlying documents.@@ -158,6 +180,7 @@ export const personaSchema = z.object({name: z.string().min(1).max(100),description: z.string().max(500).optional(),instructions: z.string().min(1).max(5000),+ traitAdjustments: personaTraitAdjustmentsSchema.optional(),createdAt: z.string().datetime(),updatedAt: z.string().datetime()});@@ -165,13 +188,16 @@ export const personaSchema = z.object({export const createPersonaInputSchema = z.object({name: z.string().min(1).max(100),description: z.string().max(500).optional(),- instructions: z.string().min(1).max(5000)+ instructions: z.string().min(1).max(5000),+ traitAdjustments: personaTraitAdjustmentsSchema.optional()});export const updatePersonaInputSchema = z.object({name: z.string().min(1).max(100).optional(),description: z.string().max(500).optional(),- instructions: z.string().min(1).max(5000).optional()+ instructions: z.string().min(1).max(5000).optional(),+ // nullable so the UI can clear adjustments back to an instructions-only persona+ traitAdjustments: personaTraitAdjustmentsSchema.nullable().optional()});export const setActivePersonaInputSchema = z.object({diff --git a/server/lib/digitalTwinValidation.test.js b/server/lib/digitalTwinValidation.test.jsindex af385901a5..9edb1d9731 100644--- a/server/lib/digitalTwinValidation.test.js+++ b/server/lib/digitalTwinValidation.test.js@@ -3,7 +3,10 @@ import {runTestsInputSchema,runMultiTestsInputSchema,createPersonaInputSchema,+ updatePersonaInputSchema,setActivePersonaInputSchema,+ personaTraitAdjustmentsSchema,+ personaSchema,digitalTwinSettingsSchema,testHistoryEntrySchema,valuesTestHistoryEntrySchema@@ -131,3 +134,57 @@ describe('persona input schemas', () => {expect(digitalTwinSettingsSchema.safeParse({}).success).toBe(true);});});++// Trait-blending (M34 P7) — personas may carry structured `traitAdjustments`.+// The schema must survive a meta round-trip (Zod strips unknown keys, so a+// missing field would silently drop the adjustments on load), bound the deltas,+// and let an update clear them with an explicit null.+describe('persona trait-blending schema', () => {+ const uuid = '11111111-1111-4111-8111-111111111111';++ it('accepts a full set of in-range adjustments', () => {+ const parsed = personaTraitAdjustmentsSchema.safeParse({+ formality: 5, verbosity: -3, emojiUsage: 'frequent', tone: 'warm', bigFive: { A: 0.4, E: -0.2 }+ });+ expect(parsed.success).toBe(true);+ });++ it('accepts an empty adjustments object (instructions-only persona)', () => {+ expect(personaTraitAdjustmentsSchema.safeParse({}).success).toBe(true);+ });++ it('rejects out-of-range communication deltas', () => {+ expect(personaTraitAdjustmentsSchema.safeParse({ formality: 10 }).success).toBe(false);+ expect(personaTraitAdjustmentsSchema.safeParse({ verbosity: -10 }).success).toBe(false);+ expect(personaTraitAdjustmentsSchema.safeParse({ formality: 2.5 }).success).toBe(false);+ });++ it('rejects out-of-range big-five deltas and bad emoji enums', () => {+ expect(personaTraitAdjustmentsSchema.safeParse({ bigFive: { O: 1.5 } }).success).toBe(false);+ expect(personaTraitAdjustmentsSchema.safeParse({ emojiUsage: 'sometimes' }).success).toBe(false);+ });++ it('round-trips traitAdjustments on a full persona record', () => {+ const persona = {+ id: uuid, name: 'Pro', instructions: 'be sharp',+ traitAdjustments: { formality: 4, bigFive: { C: 0.3 } },+ createdAt: '2025-01-01T00:00:00.000Z', updatedAt: '2025-01-01T00:00:00.000Z'+ };+ const parsed = personaSchema.parse(persona);+ expect(parsed.traitAdjustments).toEqual({ formality: 4, bigFive: { C: 0.3 } });+ });++ it('still validates a persona with no traitAdjustments (legacy)', () => {+ const parsed = personaSchema.parse({+ id: uuid, name: 'Pro', instructions: 'be sharp',+ createdAt: '2025-01-01T00:00:00.000Z', updatedAt: '2025-01-01T00:00:00.000Z'+ });+ expect(parsed.traitAdjustments).toBeUndefined();+ });++ it('lets create accept traitAdjustments and update clear them with null', () => {+ expect(createPersonaInputSchema.safeParse({ name: 'A', instructions: 'go', traitAdjustments: { formality: 2 } }).success).toBe(true);+ expect(updatePersonaInputSchema.safeParse({ traitAdjustments: null }).success).toBe(true);+ expect(updatePersonaInputSchema.safeParse({ traitAdjustments: { verbosity: 3 } }).success).toBe(true);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 4653222d90..2e7d9e30fb 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -146,6 +146,7 @@ export * from './localLlmDisk.js';export * from './issueLength.js';export * from './mediaItemKey.js';export * from './navManifest.js';+export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './planIds.js';export * from './renderSlot.js';diff --git a/server/lib/personaTraitBlend.js b/server/lib/personaTraitBlend.jsnew file mode 100644index 0000000000..a3e5d2d9a3--- /dev/null+++ b/server/lib/personaTraitBlend.js@@ -0,0 +1,223 @@+/**+ * Persona trait-blending (Digital Twin M34 P7).+ *+ * A persona is a named context (Professional, Casual, Family…). Beyond its+ * free-text `instructions`, a persona may carry structured `traitAdjustments`+ * that modulate the *base* twin's quantitative profile for that context —+ * relative nudges to the communication profile (formality / verbosity) plus+ * absolute overrides (emoji usage, tone) and directional Big-Five leans.+ *+ * This module blends those adjustments against the base twin's `traits` and+ * renders a "Communication Calibration" directive that prepends to the persona+ * preamble (see `digital-twin-context.js`), so the embodied twin shifts voice+ * per context without forking the underlying identity documents.+ *+ * Pure ESM, no Node-only deps — mirrored byte-for-byte to+ * `client/src/lib/personaTraitBlend.js` so the Personas UI can preview the same+ * directional wording. The server copy is authoritative; the matching server+ * test file (`personaTraitBlend.test.js`) is the contract.+ */++// communicationProfile.formality / .verbosity live on a 1..10 scale; a persona+// nudges them with a relative integer delta in this range.+export const COMM_DELTA_MIN = -9;+export const COMM_DELTA_MAX = 9;++// Big-Five (OCEAN) base traits live on a 0..1 scale; a persona leans them with+// a relative delta in this range.+export const BIG_FIVE_DELTA_MIN = -1;+export const BIG_FIVE_DELTA_MAX = 1;++export const BIG_FIVE_LEAN = {+ O: { more: 'more open and curious', less: 'more conventional and focused' },+ C: { more: 'more conscientious and organized', less: 'more relaxed and spontaneous' },+ E: { more: 'more outgoing and expressive', less: 'more reserved and measured' },+ A: { more: 'warmer and more accommodating', less: 'more direct and challenging' },+ N: { more: 'more emotionally expressive', less: 'more even-keeled and calm' }+};++const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));++// Bare magnitude adverb for a 1..10-scale delta (slightly / notably / much) —+// used where the paired verb already encodes direction (e.g. "more concise").+function commAdverb(delta) {+ const mag = Math.abs(delta);+ if (mag >= 5) return 'much';+ if (mag >= 3) return 'notably';+ return 'slightly';+}++// Signed wording for a fixed-quality 1..10 trait (e.g. formality): the quality+// word stays put and direction is "more"/"less" of it — "much more formal".+function commMagnitude(delta) {+ return `${commAdverb(delta)} ${delta > 0 ? 'more' : 'less'}`;+}++// Verbosity flips its quality word with sign — negative = more concise,+// positive = more elaborate — so it always reads "{adverb} more {quality}".+function verbosityPhrase(delta) {+ return `${commAdverb(delta)} more ${delta > 0 ? 'elaborate' : 'concise'}`;+}++// Magnitude wording for a 0..1-scale Big-Five delta.+function bigFiveMagnitude(delta) {+ const mag = Math.abs(delta);+ if (mag >= 0.4) return 'much';+ if (mag >= 0.2) return 'notably';+ return 'slightly';+}++/**+ * Does this persona carry any structured trait adjustment worth rendering?+ * Empty objects / all-absent fields count as "none".+ */+export function hasTraitAdjustments(adjustments) {+ if (!adjustments || typeof adjustments !== 'object') return false;+ const { formality, verbosity, emojiUsage, tone, bigFive } = adjustments;+ if (typeof formality === 'number' && formality !== 0) return true;+ if (typeof verbosity === 'number' && verbosity !== 0) return true;+ if (typeof emojiUsage === 'string' && emojiUsage) return true;+ if (typeof tone === 'string' && tone.trim()) return true;+ if (bigFive && typeof bigFive === 'object') {+ return Object.keys(BIG_FIVE_LEAN).some(k => typeof bigFive[k] === 'number' && bigFive[k] !== 0);+ }+ return false;+}++/**+ * Blend a persona's adjustments against the base communication profile,+ * returning the effective values plus the base for "X → Y" rendering. Missing+ * base values surface as `null` so callers can render a directional-only line.+ */+export function blendCommunicationProfile(baseProfile, adjustments) {+ const base = baseProfile && typeof baseProfile === 'object' ? baseProfile : {};+ const adj = adjustments && typeof adjustments === 'object' ? adjustments : {};++ const blendScale = (baseVal, delta) => {+ const hasBase = typeof baseVal === 'number';+ const hasDelta = typeof delta === 'number' && delta !== 0;+ if (!hasDelta) return { base: hasBase ? baseVal : null, effective: hasBase ? baseVal : null, delta: 0 };+ return {+ base: hasBase ? baseVal : null,+ effective: hasBase ? clamp(baseVal + delta, 1, 10) : null,+ delta+ };+ };++ return {+ formality: blendScale(base.formality, adj.formality),+ verbosity: blendScale(base.verbosity, adj.verbosity),+ emojiUsage: typeof adj.emojiUsage === 'string' && adj.emojiUsage+ ? { base: base.emojiUsage ?? null, effective: adj.emojiUsage }+ : null,+ tone: typeof adj.tone === 'string' && adj.tone.trim()+ ? { base: base.preferredTone ?? null, effective: adj.tone.trim() }+ : null+ };+}++/**+ * Human-readable, base-agnostic descriptions of each adjustment — used by the+ * Personas UI preview where the base profile isn't loaded. One short phrase per+ * active adjustment; empty array when there's nothing to say.+ */+export function describeTraitAdjustments(adjustments) {+ if (!hasTraitAdjustments(adjustments)) return [];+ const adj = adjustments;+ const lines = [];++ if (typeof adj.formality === 'number' && adj.formality !== 0) {+ lines.push(`${commMagnitude(adj.formality)} formal`);+ }+ if (typeof adj.verbosity === 'number' && adj.verbosity !== 0) {+ lines.push(verbosityPhrase(adj.verbosity));+ }+ if (typeof adj.emojiUsage === 'string' && adj.emojiUsage) {+ lines.push(`emoji usage: ${adj.emojiUsage}`);+ }+ if (typeof adj.tone === 'string' && adj.tone.trim()) {+ lines.push(`tone: ${adj.tone.trim()}`);+ }+ if (adj.bigFive && typeof adj.bigFive === 'object') {+ for (const k of Object.keys(BIG_FIVE_LEAN)) {+ const d = adj.bigFive[k];+ if (typeof d === 'number' && d !== 0) {+ const lean = d > 0 ? BIG_FIVE_LEAN[k].more : BIG_FIVE_LEAN[k].less;+ lines.push(`${bigFiveMagnitude(d)} ${lean}`);+ }+ }+ }+ return lines;+}++/**+ * Render the "Communication Calibration" directive block that prepends to a+ * persona's preamble. Blends `adjustments` against the base twin's `traits`+ * (communicationProfile + bigFive). Returns '' when the persona has no+ * adjustments so the preamble stays unchanged for instructions-only personas.+ */+export function renderTraitBlendDirective(baseTraits, adjustments, personaName = '') {+ if (!hasTraitAdjustments(adjustments)) return '';++ const traits = baseTraits && typeof baseTraits === 'object' ? baseTraits : {};+ const blended = blendCommunicationProfile(traits.communicationProfile, adjustments);+ const lines = [];++ // `phrase(delta)` returns the full directional description for this scale's+ // delta (e.g. "notably more formal" / "much more concise").+ const renderScale = (label, slot, phrase) => {+ if (!slot || slot.delta === 0) return;+ const text = phrase(slot.delta);+ if (slot.base !== null && slot.effective !== null) {+ lines.push(`- ${label}: ${slot.base} → ${slot.effective} (${text})`);+ } else {+ // No baseline recorded — render the directional intent relative to default.+ lines.push(`- ${label}: ${text} than your natural default`);+ }+ };++ renderScale('Formality', blended.formality, (d) => `${commMagnitude(d)} formal`);+ renderScale('Verbosity', blended.verbosity, verbosityPhrase);++ if (blended.emojiUsage) {+ const from = blended.emojiUsage.base ? ` (baseline ${blended.emojiUsage.base})` : '';+ lines.push(`- Emoji usage: ${blended.emojiUsage.effective}${from}`);+ }+ if (blended.tone) {+ const from = blended.tone.base ? ` (baseline ${blended.tone.base})` : '';+ lines.push(`- Tone: ${blended.tone.effective}${from}`);+ }++ // Big-Five leans, rendered as directional personality nudges.+ const adjBigFive = adjustments.bigFive && typeof adjustments.bigFive === 'object' ? adjustments.bigFive : {};+ const baseBigFive = traits.bigFive && typeof traits.bigFive === 'object' ? traits.bigFive : {};+ const leanLines = [];+ for (const k of Object.keys(BIG_FIVE_LEAN)) {+ const d = adjBigFive[k];+ if (typeof d !== 'number' || d === 0) continue;+ const lean = d > 0 ? BIG_FIVE_LEAN[k].more : BIG_FIVE_LEAN[k].less;+ const baseVal = typeof baseBigFive[k] === 'number' ? baseBigFive[k] : null;+ if (baseVal !== null) {+ const eff = clamp(baseVal + d, 0, 1);+ leanLines.push(`${bigFiveMagnitude(d)} ${lean} (${baseVal.toFixed(2)} → ${eff.toFixed(2)})`);+ } else {+ leanLines.push(`${bigFiveMagnitude(d)} ${lean}`);+ }+ }+ if (leanLines.length > 0) {+ lines.push(`- Personality lean: ${leanLines.join('; ')}`);+ }++ if (lines.length === 0) return '';++ const heading = personaName+ ? `## Communication Calibration (${personaName} context)`+ : '## Communication Calibration';++ return [+ heading,+ 'Modulate your baseline communication for this context:',+ ...lines,+ 'Where a baseline value is unknown, apply the directional adjustment relative to your natural default.'+ ].join('\n');+}diff --git a/server/lib/personaTraitBlend.test.js b/server/lib/personaTraitBlend.test.jsnew file mode 100644index 0000000000..32ae38c3d3--- /dev/null+++ b/server/lib/personaTraitBlend.test.js@@ -0,0 +1,146 @@+import { describe, it, expect } from 'vitest';+import {+ hasTraitAdjustments,+ blendCommunicationProfile,+ describeTraitAdjustments,+ renderTraitBlendDirective,+ BIG_FIVE_LEAN+} from './personaTraitBlend.js';++describe('hasTraitAdjustments', () => {+ it('returns false for absent / empty / all-zero adjustments', () => {+ expect(hasTraitAdjustments(null)).toBe(false);+ expect(hasTraitAdjustments(undefined)).toBe(false);+ expect(hasTraitAdjustments({})).toBe(false);+ expect(hasTraitAdjustments({ formality: 0, verbosity: 0 })).toBe(false);+ expect(hasTraitAdjustments({ tone: ' ' })).toBe(false);+ expect(hasTraitAdjustments({ bigFive: { O: 0, C: 0 } })).toBe(false);+ expect(hasTraitAdjustments({ bigFive: {} })).toBe(false);+ });++ it('returns true when any field carries a real adjustment', () => {+ expect(hasTraitAdjustments({ formality: 2 })).toBe(true);+ expect(hasTraitAdjustments({ verbosity: -3 })).toBe(true);+ expect(hasTraitAdjustments({ emojiUsage: 'frequent' })).toBe(true);+ expect(hasTraitAdjustments({ tone: 'warm' })).toBe(true);+ expect(hasTraitAdjustments({ bigFive: { A: 0.3 } })).toBe(true);+ });+});++describe('blendCommunicationProfile', () => {+ it('adds the delta to the base and clamps to 1..10', () => {+ const out = blendCommunicationProfile({ formality: 5, verbosity: 8 }, { formality: 3, verbosity: 5 });+ expect(out.formality).toEqual({ base: 5, effective: 8, delta: 3 });+ // 8 + 5 = 13 clamps to 10+ expect(out.verbosity).toEqual({ base: 8, effective: 10, delta: 5 });+ });++ it('clamps a downward delta at the 1 floor', () => {+ const out = blendCommunicationProfile({ formality: 2 }, { formality: -9 });+ expect(out.formality.effective).toBe(1);+ });++ it('renders directional-only (effective null) when no base value exists', () => {+ const out = blendCommunicationProfile({}, { formality: 4 });+ expect(out.formality).toEqual({ base: null, effective: null, delta: 4 });+ });++ it('returns delta 0 / passthrough when no adjustment given for a field', () => {+ const out = blendCommunicationProfile({ formality: 6 }, {});+ expect(out.formality).toEqual({ base: 6, effective: 6, delta: 0 });+ });++ it('surfaces emoji + tone overrides with their baselines', () => {+ const out = blendCommunicationProfile(+ { emojiUsage: 'rare', preferredTone: 'measured' },+ { emojiUsage: 'frequent', tone: 'playful' }+ );+ expect(out.emojiUsage).toEqual({ base: 'rare', effective: 'frequent' });+ expect(out.tone).toEqual({ base: 'measured', effective: 'playful' });+ });++ it('tolerates non-object inputs', () => {+ const out = blendCommunicationProfile(null, null);+ expect(out.formality.effective).toBeNull();+ expect(out.emojiUsage).toBeNull();+ expect(out.tone).toBeNull();+ });+});++describe('describeTraitAdjustments', () => {+ it('returns [] when there is nothing to describe', () => {+ expect(describeTraitAdjustments({})).toEqual([]);+ expect(describeTraitAdjustments(null)).toEqual([]);+ });++ it('describes formality, verbosity direction, emoji, tone, and big-five leans', () => {+ const lines = describeTraitAdjustments({+ formality: 5,+ verbosity: -3,+ emojiUsage: 'never',+ tone: 'crisp',+ bigFive: { A: 0.5, E: -0.2 }+ });+ expect(lines).toContain('much more formal');+ expect(lines).toContain('notably more concise');+ expect(lines).toContain('emoji usage: never');+ expect(lines).toContain('tone: crisp');+ expect(lines).toContain(`much ${BIG_FIVE_LEAN.A.more}`);+ expect(lines).toContain(`notably ${BIG_FIVE_LEAN.E.less}`);+ });++ it('renders positive verbosity as elaborate', () => {+ expect(describeTraitAdjustments({ verbosity: 2 })).toContain('slightly more elaborate');+ });+});++describe('renderTraitBlendDirective', () => {+ it('returns empty string when the persona has no adjustments', () => {+ expect(renderTraitBlendDirective({ communicationProfile: { formality: 5 } }, null, 'Pro')).toBe('');+ expect(renderTraitBlendDirective({}, {}, 'Pro')).toBe('');+ });++ it('renders a calibration block with base → effective transitions', () => {+ const out = renderTraitBlendDirective(+ { communicationProfile: { formality: 4, verbosity: 7 } },+ { formality: 3, verbosity: -3 },+ 'Professional'+ );+ expect(out).toContain('## Communication Calibration (Professional context)');+ expect(out).toContain('Formality: 4 → 7 (notably more formal)');+ expect(out).toContain('Verbosity: 7 → 4 (notably more concise)');+ expect(out).not.toContain('less concise');+ });++ it('renders directional intent when no base profile is recorded', () => {+ const out = renderTraitBlendDirective({}, { formality: 4 }, 'Casual');+ expect(out).toContain('Formality: notably more formal than your natural default');+ });++ it('renders emoji + tone overrides with baseline annotations', () => {+ const out = renderTraitBlendDirective(+ { communicationProfile: { emojiUsage: 'rare', preferredTone: 'measured' } },+ { emojiUsage: 'frequent', tone: 'playful' },+ 'Family'+ );+ expect(out).toContain('Emoji usage: frequent (baseline rare)');+ expect(out).toContain('Tone: playful (baseline measured)');+ });++ it('renders big-five leans with base → effective when base is known', () => {+ const out = renderTraitBlendDirective(+ { bigFive: { A: 0.5 } },+ { bigFive: { A: 0.3 } },+ 'Support'+ );+ expect(out).toContain('Personality lean:');+ expect(out).toContain(BIG_FIVE_LEAN.A.more);+ expect(out).toContain('(0.50 → 0.80)');+ });++ it('omits the persona name from the heading when none is given', () => {+ const out = renderTraitBlendDirective({}, { formality: 2 });+ expect(out).toContain('## Communication Calibration\n');+ expect(out).not.toContain('context)');+ });+});diff --git a/server/services/digital-twin-context.js b/server/services/digital-twin-context.jsindex 346853b3f3..847b1ce22b 100644--- a/server/services/digital-twin-context.js+++ b/server/services/digital-twin-context.js@@ -3,6 +3,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { DIGITAL_TWIN_DIR } from './digital-twin-helpers.js';import { loadMeta } from './digital-twin-meta.js';+import { renderTraitBlendDirective } from '../lib/personaTraitBlend.js';/*** Resolve the persona to apply for this prompt. `personaId` may be a specific@@ -19,10 +20,20 @@ function resolvePersona(meta, personaId) {return personas.find(p => p.id === id) || null;}-function buildPersonaPreamble(persona) {+/**+ * Build the persona preamble. Beyond the free-text instructions, a persona may+ * carry `traitAdjustments` that blend against the base twin's quantitative+ * `traits` (communicationProfile + bigFive) into a Communication Calibration+ * directive (P7 trait-blending). `baseTraits` is the un-flavored twin profile;+ * the directive renders relative to it, falling back to directional intent when+ * a baseline value is missing.+ */+function buildPersonaPreamble(persona, baseTraits) {if (!persona?.instructions) return '';const desc = persona.description ? `${persona.description}\n` : '';- return `# Active Persona: ${persona.name}\n${desc}\n${persona.instructions}\n\n---\n\n`;+ const calibration = renderTraitBlendDirective(baseTraits, persona.traitAdjustments, persona.name);+ const calibrationBlock = calibration ? `\n\n${calibration}` : '';+ return `# Active Persona: ${persona.name}\n${desc}\n${persona.instructions}${calibrationBlock}\n\n---\n\n`;}export async function getDigitalTwinForPrompt(options = {}) {@@ -34,8 +45,10 @@ export async function getDigitalTwinForPrompt(options = {}) {}// A persona's instructions are always included (they're the active directive)- // and prepended before the documents, counting toward the token budget.- const preamble = buildPersonaPreamble(resolvePersona(meta, personaId));+ // and prepended before the documents, counting toward the token budget. When+ // the persona carries trait adjustments, they blend against the base twin's+ // quantitative traits into a Communication Calibration directive.+ const preamble = buildPersonaPreamble(resolvePersona(meta, personaId), meta.traits);// Get enabled documents sorted by weight (desc) then priority (asc)// Higher weight = more important = included firstdiff --git a/server/services/digital-twin-personas.js b/server/services/digital-twin-personas.jsindex 655c61116a..a6c23c3be2 100644--- a/server/services/digital-twin-personas.js+++ b/server/services/digital-twin-personas.js@@ -25,7 +25,7 @@ export async function getPersonaById(id) {return personas.find(p => p.id === id) || null;}-export async function createPersona({ name, description, instructions }) {+export async function createPersona({ name, description, instructions, traitAdjustments }) {const meta = await loadMeta();if (!Array.isArray(meta.personas)) meta.personas = [];@@ -35,6 +35,7 @@ export async function createPersona({ name, description, instructions }) {name,...(description ? { description } : {}),instructions,+ ...(traitAdjustments ? { traitAdjustments } : {}),createdAt: timestamp,updatedAt: timestamp};@@ -57,6 +58,15 @@ export async function updatePersona(id, updates) {if (updates.name !== undefined) persona.name = updates.name;if (updates.description !== undefined) persona.description = updates.description;if (updates.instructions !== undefined) persona.instructions = updates.instructions;+ // traitAdjustments: absent (undefined) preserves the original; an explicit+ // null clears it back to an instructions-only persona; an object replaces it.+ if (updates.traitAdjustments !== undefined) {+ if (updates.traitAdjustments === null) {+ delete persona.traitAdjustments;+ } else {+ persona.traitAdjustments = updates.traitAdjustments;+ }+ }persona.updatedAt = now();await saveMeta(meta);diff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.jsindex e5e34d9e86..258b31f2b1 100644--- a/server/services/digital-twin.test.js+++ b/server/services/digital-twin.test.js@@ -1478,6 +1478,56 @@ Forgets the budget and recommends lodging that exceeds it.expect(result).not.toContain('Active Persona');expect(result).toContain('Soul content');});++ it('renders a Communication Calibration directive when the persona carries trait adjustments (P7)', async () => {+ const persona = {+ id: 'p1', name: 'Professional', instructions: 'Be concise and formal.',+ traitAdjustments: { formality: 3, verbosity: -2, bigFive: { A: 0.3 } },+ createdAt: '2025-01-01T00:00:00.000Z', updatedAt: '2025-01-01T00:00:00.000Z'+ };+ const meta = makeMeta({+ documents: [makeDocMeta({ id: 'doc-1', filename: 'SOUL.md', weight: 10 })],+ personas: [persona],+ traits: { communicationProfile: { formality: 4, verbosity: 7 }, bigFive: { A: 0.5 } },+ settings: { autoInjectToCoS: true, maxContextTokens: 4000, activePersonaId: 'p1' }+ });+ await saveMeta(meta);+ readFile.mockImplementation(async (filePath) => {+ if (filePath.includes('meta.json')) return JSON.stringify(meta);+ if (filePath.includes('SOUL.md')) return 'Soul content';+ return '';+ });++ const result = await getDigitalTwinForPrompt({ personaId: 'active' });+ expect(result).toContain('# Active Persona: Professional');+ expect(result).toContain('## Communication Calibration (Professional context)');+ expect(result).toContain('Formality: 4 → 7'); // 4 + 3 = 7+ expect(result).toContain('Verbosity: 7 → 5'); // 7 - 2 = 5, "more concise"+ expect(result).toContain('Soul content');+ });++ it('omits the calibration directive for an instructions-only persona', async () => {+ const persona = {+ id: 'p1', name: 'Casual', instructions: 'Be relaxed.',+ createdAt: '2025-01-01T00:00:00.000Z', updatedAt: '2025-01-01T00:00:00.000Z'+ };+ const meta = makeMeta({+ documents: [makeDocMeta({ id: 'doc-1', filename: 'SOUL.md', weight: 10 })],+ personas: [persona],+ traits: { communicationProfile: { formality: 4 } },+ settings: { autoInjectToCoS: true, maxContextTokens: 4000, activePersonaId: 'p1' }+ });+ await saveMeta(meta);+ readFile.mockImplementation(async (filePath) => {+ if (filePath.includes('meta.json')) return JSON.stringify(meta);+ if (filePath.includes('SOUL.md')) return 'Soul content';+ return '';+ });++ const result = await getDigitalTwinForPrompt({ personaId: 'active' });+ expect(result).toContain('# Active Persona: Casual');+ expect(result).not.toContain('Communication Calibration');+ });});// ==========================================================================@@ -1525,6 +1575,28 @@ Forgets the budget and recommends lodging that exceeds it.await expect(updatePersona('does-not-exist', { name: 'x' })).rejects.toThrow();});+ it('stores traitAdjustments on create and omits the key when absent (P7)', async () => {+ await setupMetaFile(makeMeta());+ const withAdj = await createPersona({ name: 'Pro', instructions: 'go', traitAdjustments: { formality: 3 } });+ expect(withAdj.traitAdjustments).toEqual({ formality: 3 });+ const without = await createPersona({ name: 'Plain', instructions: 'go' });+ expect(without.traitAdjustments).toBeUndefined();+ });++ it('updates, preserves (absent), and clears (null) traitAdjustments (P7)', async () => {+ await setupMetaFile(makeMeta());+ const persona = await createPersona({ name: 'A', instructions: 'one', traitAdjustments: { formality: 2 } });+ // Absent → preserved.+ const preserved = await updatePersona(persona.id, { instructions: 'two' });+ expect(preserved.traitAdjustments).toEqual({ formality: 2 });+ // Object → replaced.+ const replaced = await updatePersona(persona.id, { traitAdjustments: { verbosity: -3 } });+ expect(replaced.traitAdjustments).toEqual({ verbosity: -3 });+ // Null → cleared back to instructions-only.+ const cleared = await updatePersona(persona.id, { traitAdjustments: null });+ expect(cleared.traitAdjustments).toBeUndefined();+ });+it('sets and reads back the active persona', async () => {await setupMetaFile(makeMeta());const persona = await createPersona({ name: 'A', instructions: 'one' });