Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-708]): add Twin Personas with active-persona context switching (M34 P7)

[._.]/ Adam Eivyb9150b6e1e6f
diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.js
index 1490dcdd8d..beede38410 100644
--- a/client/src/components/digital-twin/constants.js
+++ b/client/src/components/digital-twin/constants.js
@@ -25,7 +25,8 @@ import {
Globe,
PenLine,
Target,
- Archive
+ Archive,
+ Drama
} from 'lucide-react';
// Main navigation tabs
@@ -37,6 +38,7 @@ export const TABS = [
{ id: 'taste', label: 'Taste', icon: Palette },
{ id: 'accounts', label: 'Accounts', icon: Globe },
{ id: 'identity', label: 'Identity', icon: Fingerprint },
+ { id: 'personas', label: 'Personas', icon: Drama },
{ id: 'goals', label: 'Goals', icon: Target },
{ id: 'interview', label: 'Interview', icon: MessageSquare },
{ id: 'autobiography', label: 'Autobiography', icon: PenLine },
diff --git a/client/src/components/digital-twin/tabs/PersonasTab.jsx b/client/src/components/digital-twin/tabs/PersonasTab.jsx
new file mode 100644
index 0000000000..589b557707
--- /dev/null
+++ b/client/src/components/digital-twin/tabs/PersonasTab.jsx
@@ -0,0 +1,322 @@
+import { useState, useEffect } from 'react';
+import { Drama, Plus, Pencil, Trash2, Check, X, CheckCircle2 } from 'lucide-react';
+import BrailleSpinner from '../../BrailleSpinner';
+import * as api from '../../../services/api';
+import toast from '../../ui/Toast';
+
+const EMPTY_FORM = { name: '', description: '', instructions: '' };
+
+/**
+ * Twin Personas (M34 P7). Named context variants whose instructions are
+ * prepended to the embodied-twin context. The active persona flavors the
+ * context that CoS agents see; identity-building flows stay persona-free.
+ */
+export default function PersonasTab({ onRefresh }) {
+ const [personas, setPersonas] = useState([]);
+ const [activeId, setActiveId] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState(false);
+
+ const [showCreate, setShowCreate] = useState(false);
+ const [createForm, setCreateForm] = useState(EMPTY_FORM);
+
+ const [editingId, setEditingId] = useState(null);
+ const [editForm, setEditForm] = useState(EMPTY_FORM);
+
+ const [confirmDeleteId, setConfirmDeleteId] = useState(null);
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ const loadData = async () => {
+ setLoading(true);
+ const [personaData, settings] = await Promise.all([
+ api.getDigitalTwinPersonas().catch(() => []),
+ api.getDigitalTwinSettings({ silent: true }).catch(() => ({}))
+ ]);
+ setPersonas(personaData);
+ setActiveId(settings?.activePersonaId ?? null);
+ setLoading(false);
+ };
+
+ const createPersona = async () => {
+ if (!createForm.name.trim() || !createForm.instructions.trim()) {
+ toast.error('Name and instructions are required');
+ return;
+ }
+ setBusy(true);
+ const persona = await api.createDigitalTwinPersona({
+ name: createForm.name.trim(),
+ description: createForm.description.trim() || undefined,
+ instructions: createForm.instructions.trim()
+ }).catch(() => null);
+ setBusy(false);
+ if (!persona) return;
+ setPersonas(prev => [...prev, persona]);
+ setCreateForm(EMPTY_FORM);
+ setShowCreate(false);
+ toast.success('Persona created');
+ onRefresh?.();
+ };
+
+ const startEdit = (persona) => {
+ setEditingId(persona.id);
+ setEditForm({
+ name: persona.name,
+ description: persona.description || '',
+ instructions: persona.instructions
+ });
+ };
+
+ const saveEdit = async (id) => {
+ if (!editForm.name.trim() || !editForm.instructions.trim()) {
+ toast.error('Name and instructions are required');
+ return;
+ }
+ setBusy(true);
+ const updated = await api.updateDigitalTwinPersona(id, {
+ name: editForm.name.trim(),
+ description: editForm.description.trim(),
+ instructions: editForm.instructions.trim()
+ }).catch(() => null);
+ setBusy(false);
+ if (!updated) return;
+ setPersonas(prev => prev.map(p => (p.id === id ? updated : p)));
+ setEditingId(null);
+ toast.success('Persona updated');
+ onRefresh?.();
+ };
+
+ const removePersona = async (id) => {
+ setBusy(true);
+ const ok = await api.deleteDigitalTwinPersona(id).then(() => true).catch(() => false);
+ setBusy(false);
+ setConfirmDeleteId(null);
+ if (!ok) return;
+ setPersonas(prev => prev.filter(p => p.id !== id));
+ if (activeId === id) setActiveId(null); // server clears the active pointer too
+ toast.success('Persona deleted');
+ onRefresh?.();
+ };
+
+ const toggleActive = async (id) => {
+ const next = activeId === id ? null : id;
+ setBusy(true);
+ const ok = await api.setActiveDigitalTwinPersona(next).then(() => true).catch(() => false);
+ setBusy(false);
+ if (!ok) return;
+ setActiveId(next);
+ toast.success(next ? 'Persona activated' : 'Persona deactivated');
+ onRefresh?.();
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <BrailleSpinner text="Loading personas" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
+ <div>
+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">
+ <Drama className="w-5 h-5 text-port-accent" />
+ Personas
+ </h2>
+ <p className="text-sm text-gray-500 mt-1 max-w-2xl">
+ A persona is a named context (Professional, Casual, Family…) whose instructions are prepended to your twin.
+ The <span className="text-gray-300">active</span> persona flavors the context your CoS agents act with — building your base identity stays unaffected.
+ </p>
+ </div>
+ {!showCreate && (
+ <button
+ onClick={() => { setShowCreate(true); setCreateForm(EMPTY_FORM); }}
+ className="flex items-center justify-center gap-2 px-4 py-2.5 min-h-[44px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 shrink-0"
+ >
+ <Plus className="w-4 h-4" />
+ New Persona
+ </button>
+ )}
+ </div>
+
+ {/* Create form */}
+ {showCreate && (
+ <div className="bg-port-card rounded-lg border border-port-accent/30 p-4 space-y-3">
+ <h3 className="font-semibold text-white">New Persona</h3>
+ <PersonaForm form={createForm} setForm={setCreateForm} idPrefix="persona-create" />
+ <div className="flex gap-2">
+ <button
+ onClick={createPersona}
+ disabled={busy}
+ className="flex items-center gap-2 px-4 py-2 min-h-[40px] bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ <Check className="w-4 h-4" /> Create
+ </button>
+ <button
+ onClick={() => { setShowCreate(false); setCreateForm(EMPTY_FORM); }}
+ className="flex items-center gap-2 px-4 py-2 min-h-[40px] border border-port-border text-gray-400 rounded-lg hover:text-white"
+ >
+ <X className="w-4 h-4" /> Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Persona list */}
+ {personas.length === 0 && !showCreate ? (
+ <div className="flex flex-col items-center justify-center h-48 text-center text-gray-400">
+ <Drama className="w-10 h-10 mb-3 text-gray-600" />
+ <p className="max-w-md">No personas yet. Create one to give your twin a context — like a focused "Professional" voice or a relaxed "Family" tone — and activate it to shape how your agents speak and decide.</p>
+ </div>
+ ) : (
+ <div className="space-y-3">
+ {personas.map(persona => {
+ const isActive = activeId === persona.id;
+ const isEditing = editingId === persona.id;
+ return (
+ <div
+ key={persona.id}
+ className={`bg-port-card rounded-lg border p-4 ${isActive ? 'border-port-accent' : 'border-port-border'}`}
+ >
+ {isEditing ? (
+ <div className="space-y-3">
+ <PersonaForm form={editForm} setForm={setEditForm} idPrefix={`persona-edit-${persona.id}`} />
+ <div className="flex gap-2">
+ <button
+ onClick={() => saveEdit(persona.id)}
+ disabled={busy}
+ className="flex items-center gap-2 px-4 py-2 min-h-[40px] bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ <Check className="w-4 h-4" /> Save
+ </button>
+ <button
+ onClick={() => setEditingId(null)}
+ className="flex items-center gap-2 px-4 py-2 min-h-[40px] border border-port-border text-gray-400 rounded-lg hover:text-white"
+ >
+ <X className="w-4 h-4" /> Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <>
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="font-medium text-white">{persona.name}</span>
+ {isActive && (
+ <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded bg-port-accent/20 text-port-accent">
+ <CheckCircle2 className="w-3 h-3" /> Active
+ </span>
+ )}
+ </div>
+ {persona.description && (
+ <p className="text-sm text-gray-400 mt-1">{persona.description}</p>
+ )}
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ <button
+ onClick={() => toggleActive(persona.id)}
+ disabled={busy}
+ className={`px-3 py-1.5 min-h-[36px] text-xs rounded-lg border transition-colors disabled:opacity-50 ${
+ isActive
+ ? 'border-port-accent text-port-accent hover:bg-port-accent/10'
+ : 'border-port-border text-gray-400 hover:text-white hover:border-gray-500'
+ }`}
+ >
+ {isActive ? 'Deactivate' : 'Set active'}
+ </button>
+ <button
+ onClick={() => startEdit(persona)}
+ aria-label="Edit persona"
+ className="p-2 min-h-[36px] text-gray-400 hover:text-white rounded-lg"
+ >
+ <Pencil className="w-4 h-4" />
+ </button>
+ <button
+ onClick={() => setConfirmDeleteId(persona.id)}
+ aria-label="Delete persona"
+ className="p-2 min-h-[36px] text-gray-400 hover:text-port-error rounded-lg"
+ >
+ <Trash2 className="w-4 h-4" />
+ </button>
+ </div>
+ </div>
+ <p className="text-sm text-gray-300 mt-3 whitespace-pre-wrap bg-port-bg p-3 rounded">{persona.instructions}</p>
+
+ {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>
+ <div className="flex gap-2">
+ <button
+ onClick={() => removePersona(persona.id)}
+ disabled={busy}
+ className="px-3 py-1.5 min-h-[36px] text-xs bg-port-error/20 text-port-error rounded-lg hover:bg-port-error/30 disabled:opacity-50"
+ >
+ Delete
+ </button>
+ <button
+ onClick={() => setConfirmDeleteId(null)}
+ className="px-3 py-1.5 min-h-[36px] text-xs border border-port-border text-gray-400 rounded-lg hover:text-white"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function PersonaForm({ form, setForm, idPrefix }) {
+ return (
+ <div className="space-y-3">
+ <div>
+ <label htmlFor={`${idPrefix}-name`} className="block text-sm text-gray-400 mb-1">Name</label>
+ <input
+ id={`${idPrefix}-name`}
+ type="text"
+ value={form.name}
+ onChange={(e) => setForm(f => ({ ...f, name: e.target.value }))}
+ placeholder="e.g. Professional"
+ 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>
+ <label htmlFor={`${idPrefix}-description`} className="block text-sm text-gray-400 mb-1">Description <span className="text-gray-600">(optional)</span></label>
+ <input
+ id={`${idPrefix}-description`}
+ type="text"
+ value={form.description}
+ onChange={(e) => setForm(f => ({ ...f, description: e.target.value }))}
+ placeholder="When to use this persona"
+ maxLength={500}
+ 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>
+ <label htmlFor={`${idPrefix}-instructions`} className="block text-sm text-gray-400 mb-1">Instructions</label>
+ <textarea
+ id={`${idPrefix}-instructions`}
+ value={form.instructions}
+ onChange={(e) => setForm(f => ({ ...f, instructions: e.target.value }))}
+ placeholder="How the twin should modulate voice and behavior in this context — e.g. 'Be concise and formal; avoid personal anecdotes; lead with the recommendation.'"
+ rows={4}
+ maxLength={5000}
+ 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>
+ </div>
+ );
+}
diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsx
index 09d444f31a..c184980569 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -17,6 +17,7 @@ import TasteTab from '../components/digital-twin/tabs/TasteTab';
import AccountsTab from '../components/digital-twin/tabs/AccountsTab';
import InterviewTab from '../components/digital-twin/tabs/InterviewTab';
import IdentityTab from '../components/digital-twin/tabs/IdentityTab';
+import PersonasTab from '../components/digital-twin/tabs/PersonasTab';
import GoalsTab from '../components/digital-twin/tabs/GoalsTab';
import AutobiographyTab from '../components/digital-twin/tabs/AutobiographyTab';
import ImportTab from '../components/digital-twin/tabs/ImportTab';
@@ -65,6 +66,8 @@ export default function DigitalTwin() {
return <AccountsTab />;
case 'identity':
return <IdentityTab onRefresh={refetch} />;
+ case 'personas':
+ return <PersonasTab onRefresh={refetch} />;
case 'goals':
return <GoalsTab onRefresh={refetch} />;
case 'interview':
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index acdbb6f626..3dce656053 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -62,6 +62,22 @@ export const updateDigitalTwinSettings = (settings) => request('/digital-twin/se
body: JSON.stringify(settings)
});
+// Digital Twin - Personas (M34 P7)
+export const getDigitalTwinPersonas = () => request('/digital-twin/personas');
+export const createDigitalTwinPersona = (data) => request('/digital-twin/personas', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateDigitalTwinPersona = (id, data) => request(`/digital-twin/personas/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteDigitalTwinPersona = (id) => request(`/digital-twin/personas/${id}`, { method: 'DELETE' });
+export const setActiveDigitalTwinPersona = (personaId) => request('/digital-twin/personas/active', {
+ method: 'PUT',
+ body: JSON.stringify({ personaId })
+});
+
// Digital Twin - Validation & Analysis
export const getDigitalTwinCompleteness = () => request('/digital-twin/validate/completeness');
export const detectDigitalTwinContradictions = (providerId, model) => request('/digital-twin/validate/contradictions', {
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index 259de3a71a..eceb07f3e5 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -101,10 +101,43 @@ export const enrichmentProgressSchema = z.object({
// Digital Twin settings schema
export const digitalTwinSettingsSchema = z.object({
autoInjectToCoS: z.boolean().default(true),
- maxContextTokens: z.number().int().min(1000).max(100000).default(4000)
+ maxContextTokens: z.number().int().min(1000).max(100000).default(4000),
+ // The persona currently driving the embodied-twin context (CoS agents, etc.).
+ // null/absent = no persona (base twin). Tolerate the UI sentinel for "deactivate".
+ activePersonaId: z.string().uuid().nullable().optional()
});
export const soulSettingsSchema = digitalTwinSettingsSchema; // Alias for backwards compatibility
+// --- Phase 7: Twin Personas (M34 P7) ---
+
+// 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.
+export const personaSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string().min(1).max(100),
+ description: z.string().max(500).optional(),
+ instructions: z.string().min(1).max(5000),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime()
+});
+
+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)
+});
+
+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()
+});
+
+export const setActivePersonaInputSchema = z.object({
+ personaId: z.string().uuid().nullable()
+});
+
// --- Phase 1: Quantitative Personality Modeling Schemas ---
// Big Five personality traits (OCEAN model)
@@ -177,6 +210,7 @@ export const digitalTwinMetaSchema = z.object({
valuesTestHistory: z.array(valuesTestHistoryEntrySchema).default([]),
enrichment: enrichmentProgressSchema.default({ completedCategories: [], lastSession: null }),
settings: digitalTwinSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000 }),
+ personas: z.array(personaSchema).default([]),
traits: traitsSchema.optional(),
confidence: confidenceSchema.optional()
});
diff --git a/server/lib/digitalTwinValidation.test.js b/server/lib/digitalTwinValidation.test.js
index d0004ce387..a27c60997b 100644
--- a/server/lib/digitalTwinValidation.test.js
+++ b/server/lib/digitalTwinValidation.test.js
@@ -1,5 +1,11 @@
import { describe, it, expect } from 'vitest';
-import { runTestsInputSchema, runMultiTestsInputSchema } from './digitalTwinValidation.js';
+import {
+ runTestsInputSchema,
+ runMultiTestsInputSchema,
+ createPersonaInputSchema,
+ setActivePersonaInputSchema,
+ digitalTwinSettingsSchema
+} from './digitalTwinValidation.js';
// Regression guard: the client API wrappers default `testIds` to `null` for a
// "run all tests" request. A bare `.optional()` rejects null and would 400
@@ -31,3 +37,27 @@ describe('runTestsInputSchema testIds null-tolerance', () => {
expect(parsed.testIds).toBeUndefined();
});
});
+
+// Personas (M34 P7) — validate the create/active input contracts and that the
+// settings schema accepts the activePersonaId pointer (including null = clear).
+describe('persona input schemas', () => {
+ const uuid = '11111111-1111-4111-8111-111111111111';
+
+ it('requires name and instructions to create a persona', () => {
+ expect(createPersonaInputSchema.safeParse({ name: 'A', instructions: 'go' }).success).toBe(true);
+ expect(createPersonaInputSchema.safeParse({ name: '', instructions: 'go' }).success).toBe(false);
+ expect(createPersonaInputSchema.safeParse({ name: 'A' }).success).toBe(false);
+ });
+
+ it('accepts a uuid or null for the active persona pointer', () => {
+ expect(setActivePersonaInputSchema.safeParse({ personaId: uuid }).success).toBe(true);
+ expect(setActivePersonaInputSchema.safeParse({ personaId: null }).success).toBe(true);
+ expect(setActivePersonaInputSchema.safeParse({ personaId: 'not-a-uuid' }).success).toBe(false);
+ });
+
+ it('lets settings carry activePersonaId (uuid or null)', () => {
+ expect(digitalTwinSettingsSchema.safeParse({ activePersonaId: uuid }).success).toBe(true);
+ expect(digitalTwinSettingsSchema.safeParse({ activePersonaId: null }).success).toBe(true);
+ expect(digitalTwinSettingsSchema.safeParse({}).success).toBe(true);
+ });
+});
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 829f25dabe..eb9a53bee9 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -112,6 +112,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.twin.identity', path: '/digital-twin/identity', label: 'Identity', section: 'Digital Twin', aliases: ['twin-identity', 'identity'] },
{ id: 'nav.twin.import', path: '/digital-twin/import', label: 'Import', section: 'Digital Twin', aliases: ['twin-import'] },
{ id: 'nav.twin.interview', path: '/digital-twin/interview', label: 'Interview', section: 'Digital Twin', aliases: ['twin-interview'] },
+ { id: 'nav.twin.personas', path: '/digital-twin/personas', label: 'Personas', section: 'Digital Twin', aliases: ['twin-personas', 'personas', 'persona'], keywords: ['context', 'professional', 'casual', 'voice', 'mode'] },
{ id: 'nav.twin.taste', path: '/digital-twin/taste', label: 'Taste', section: 'Digital Twin', aliases: ['twin-taste'] },
{ id: 'nav.twin.test', path: '/digital-twin/test', label: 'Test', section: 'Digital Twin', aliases: ['twin-test'] },
{ id: 'nav.twin.time-capsule', path: '/digital-twin/time-capsule', label: 'Time Capsule', section: 'Digital Twin', aliases: ['time-capsule', 'twin-time-capsule', 'capsule'], keywords: ['legacy', 'archive', 'snapshot'] },
diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.js
index b81eea584e..09840c9bb7 100644
--- a/server/routes/digital-twin.js
+++ b/server/routes/digital-twin.js
@@ -42,7 +42,10 @@ import {
tastePersonalizedQuestionInputSchema,
feedbackInputSchema,
createSnapshotInputSchema,
- compareSnapshotsInputSchema
+ compareSnapshotsInputSchema,
+ createPersonaInputSchema,
+ updatePersonaInputSchema,
+ setActivePersonaInputSchema
} from '../lib/digitalTwinValidation.js';
import * as timeCapsuleService from '../services/timeCapsule.js';
import { UUID_RE } from '../lib/fileUtils.js';
@@ -336,6 +339,82 @@ router.put('/settings', asyncHandler(async (req, res) => {
res.json(settings);
}));
+// =============================================================================
+// PERSONAS (M34 P7)
+// =============================================================================
+
+/**
+ * GET /api/digital-twin/personas
+ * List all twin personas
+ */
+router.get('/personas', asyncHandler(async (req, res) => {
+ res.json(await digitalTwinService.getPersonas());
+}));
+
+/**
+ * POST /api/digital-twin/personas
+ * Create a new persona
+ */
+router.post('/personas', asyncHandler(async (req, res) => {
+ const data = validateRequest(createPersonaInputSchema, req.body);
+ const persona = await digitalTwinService.createPersona(data);
+ res.status(201).json(persona);
+}));
+
+/**
+ * GET /api/digital-twin/personas/active
+ * Get the currently active persona (null when none is set)
+ * (Registered before /personas/:id so "active" isn't matched as an id.)
+ */
+router.get('/personas/active', asyncHandler(async (req, res) => {
+ res.json(await digitalTwinService.getActivePersona());
+}));
+
+/**
+ * PUT /api/digital-twin/personas/active
+ * Set (or clear, with personaId: null) the active persona
+ */
+router.put('/personas/active', asyncHandler(async (req, res) => {
+ const { personaId } = validateRequest(setActivePersonaInputSchema, req.body);
+ if (personaId && !(await digitalTwinService.getPersonaById(personaId))) {
+ throw new ServerError('Persona not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const settings = await digitalTwinService.setActivePersona(personaId);
+ res.json(settings);
+}));
+
+/**
+ * PUT /api/digital-twin/personas/:id
+ * Update a persona
+ */
+router.put('/personas/:id', asyncHandler(async (req, res) => {
+ const { id } = req.params;
+ if (!UUID_RE.test(id)) {
+ throw new ServerError('Invalid persona id', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const data = validateRequest(updatePersonaInputSchema, req.body);
+ if (!(await digitalTwinService.getPersonaById(id))) {
+ throw new ServerError('Persona not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(await digitalTwinService.updatePersona(id, data));
+}));
+
+/**
+ * DELETE /api/digital-twin/personas/:id
+ * Delete a persona (clears the active pointer if it was active)
+ */
+router.delete('/personas/:id', asyncHandler(async (req, res) => {
+ const { id } = req.params;
+ if (!UUID_RE.test(id)) {
+ throw new ServerError('Invalid persona id', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const { deleted } = await digitalTwinService.deletePersona(id);
+ if (!deleted) {
+ throw new ServerError('Persona not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json({ success: true });
+}));
+
// =============================================================================
// VALIDATION & ANALYSIS
// =============================================================================
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index e821ed6dbd..44bcd0930d 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -429,7 +429,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
? Promise.resolve(null)
: getClaudeMdContext(workspaceDir)
.catch(err => { console.log(`⚠️ CLAUDE.md retrieval failed: ${err.message}`); return null; }),
- getDigitalTwinForPrompt({ maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000 })
+ getDigitalTwinForPrompt({ maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000, personaId: 'active' })
.catch(err => { console.log(`⚠️ Digital twin context retrieval failed: ${err.message}`); return null; })
]);
diff --git a/server/services/digital-twin-context.js b/server/services/digital-twin-context.js
index f41694674e..346853b3f3 100644
--- a/server/services/digital-twin-context.js
+++ b/server/services/digital-twin-context.js
@@ -4,14 +4,39 @@ import { join } from 'path';
import { DIGITAL_TWIN_DIR } from './digital-twin-helpers.js';
import { loadMeta } from './digital-twin-meta.js';
+/**
+ * Resolve the persona to apply for this prompt. `personaId` may be a specific
+ * id, the string 'active' (resolve from settings.activePersonaId), or
+ * undefined/null (no persona). Returns the persona record or null — callers
+ * that build the *base* twin (enrichment, trait analysis) pass nothing and get
+ * the un-flavored context; embody paths (CoS agents) pass 'active'.
+ */
+function resolvePersona(meta, personaId) {
+ if (personaId === undefined || personaId === null) return null;
+ const id = personaId === 'active' ? meta.settings?.activePersonaId : personaId;
+ if (!id) return null;
+ const personas = Array.isArray(meta.personas) ? meta.personas : [];
+ return personas.find(p => p.id === id) || null;
+}
+
+function buildPersonaPreamble(persona) {
+ 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`;
+}
+
export async function getDigitalTwinForPrompt(options = {}) {
- const { maxTokens = 4000 } = options;
+ const { maxTokens = 4000, personaId } = options;
const meta = await loadMeta();
if (!meta.settings.autoInjectToCoS) {
return '';
}
+ // 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));
+
// Get enabled documents sorted by weight (desc) then priority (asc)
// Higher weight = more important = included first
const docs = meta.documents
@@ -23,8 +48,8 @@ export async function getDigitalTwinForPrompt(options = {}) {
return a.priority - b.priority; // Then by priority
});
- let output = '';
- let tokenCount = 0;
+ let output = preamble;
+ let tokenCount = preamble.length;
const maxChars = maxTokens * 4; // Rough char-to-token estimate
for (const doc of docs) {
diff --git a/server/services/digital-twin-meta.js b/server/services/digital-twin-meta.js
index 937829316f..762674d9c4 100644
--- a/server/services/digital-twin-meta.js
+++ b/server/services/digital-twin-meta.js
@@ -29,6 +29,7 @@ export const DEFAULT_META = {
documents: [],
testHistory: [],
valuesTestHistory: [],
+ personas: [],
enrichment: { completedCategories: [], lastSession: null },
settings: { autoInjectToCoS: true, maxContextTokens: 4000 }
};
diff --git a/server/services/digital-twin-personas.js b/server/services/digital-twin-personas.js
new file mode 100644
index 0000000000..655c61116a
--- /dev/null
+++ b/server/services/digital-twin-personas.js
@@ -0,0 +1,101 @@
+/**
+ * Digital Twin — Twin Personas (M34 P7)
+ *
+ * A persona is a named context variant (Professional, Casual, Family, …) whose
+ * `instructions` are prepended to the embodied-twin context so the twin
+ * modulates voice/behavior per context without forking the underlying
+ * documents. One persona can be marked "active" (`meta.settings.activePersonaId`);
+ * the CoS agent prompt builder asks for the active persona, while the
+ * identity-building paths (enrichment, analysis) stay persona-free.
+ *
+ * Personas live in `meta.personas`, mirroring how testHistory / enrichment
+ * already live in meta.json.
+ */
+
+import { generateId, now } from './digital-twin-helpers.js';
+import { loadMeta, saveMeta } from './digital-twin-meta.js';
+
+export async function getPersonas() {
+ const meta = await loadMeta();
+ return Array.isArray(meta.personas) ? meta.personas : [];
+}
+
+export async function getPersonaById(id) {
+ const personas = await getPersonas();
+ return personas.find(p => p.id === id) || null;
+}
+
+export async function createPersona({ name, description, instructions }) {
+ const meta = await loadMeta();
+ if (!Array.isArray(meta.personas)) meta.personas = [];
+
+ const timestamp = now();
+ const persona = {
+ id: generateId(),
+ name,
+ ...(description ? { description } : {}),
+ instructions,
+ createdAt: timestamp,
+ updatedAt: timestamp
+ };
+
+ meta.personas.push(persona);
+ await saveMeta(meta);
+ console.log(`🎭 Created persona: ${name}`);
+ return persona;
+}
+
+export async function updatePersona(id, updates) {
+ const meta = await loadMeta();
+ const persona = (meta.personas || []).find(p => p.id === id);
+ if (!persona) {
+ throw new Error(`Persona ${id} not found`);
+ }
+
+ // Only apply keys that were actually provided so an omitted field preserves
+ // the original (and description: '' can intentionally clear it).
+ if (updates.name !== undefined) persona.name = updates.name;
+ if (updates.description !== undefined) persona.description = updates.description;
+ if (updates.instructions !== undefined) persona.instructions = updates.instructions;
+ persona.updatedAt = now();
+
+ await saveMeta(meta);
+ return persona;
+}
+
+export async function deletePersona(id) {
+ const meta = await loadMeta();
+ const before = (meta.personas || []).length;
+ meta.personas = (meta.personas || []).filter(p => p.id !== id);
+
+ // Clearing the active persona when it's the one being deleted keeps the
+ // settings pointer from dangling at a non-existent id.
+ if (meta.settings?.activePersonaId === id) {
+ meta.settings.activePersonaId = null;
+ }
+
+ await saveMeta(meta);
+ return { deleted: before !== meta.personas.length };
+}
+
+/**
+ * Set (or clear, with personaId === null) the active persona. Validates the id
+ * exists so the settings pointer can't dangle.
+ */
+export async function setActivePersona(personaId) {
+ const meta = await loadMeta();
+ if (personaId !== null && !(meta.personas || []).some(p => p.id === personaId)) {
+ throw new Error(`Persona ${personaId} not found`);
+ }
+ if (!meta.settings) meta.settings = {};
+ meta.settings.activePersonaId = personaId;
+ await saveMeta(meta);
+ return meta.settings;
+}
+
+export async function getActivePersona() {
+ const meta = await loadMeta();
+ const id = meta.settings?.activePersonaId;
+ if (!id) return null;
+ return (meta.personas || []).find(p => p.id === id) || null;
+}
diff --git a/server/services/digital-twin.js b/server/services/digital-twin.js
index 1f221090e6..94006ecaa4 100644
--- a/server/services/digital-twin.js
+++ b/server/services/digital-twin.js
@@ -8,6 +8,7 @@
* digital-twin-documents.js — getDocuments, getDocumentById, createDocument, updateDocument, deleteDocument
* digital-twin-testing.js — parseTestSuite, runTests, getTestHistory
* digital-twin-values-testing.js — parseValuesAlignmentSuite, runValuesAlignmentTests, getValuesAlignmentHistory
+ * digital-twin-personas.js — getPersonas, createPersona, updatePersona, deletePersona, setActivePersona, getActivePersona
* digital-twin-enrichment.js — getEnrichmentCategories, generateEnrichmentQuestion, processEnrichmentAnswer, …
* digital-twin-export.js — getExportFormats, exportDigitalTwin, exportSoul
* digital-twin-context.js — getDigitalTwinForPrompt, getSoulForPrompt
@@ -46,6 +47,16 @@ export {
getValuesAlignmentHistory
} from './digital-twin-values-testing.js';
+export {
+ getPersonas,
+ getPersonaById,
+ createPersona,
+ updatePersona,
+ deletePersona,
+ setActivePersona,
+ getActivePersona
+} from './digital-twin-personas.js';
+
export {
getEnrichmentCategories,
generateEnrichmentQuestion,
diff --git a/server/services/digital-twin.test.js b/server/services/digital-twin.test.js
index 90c97b21a5..8c1566e48f 100644
--- a/server/services/digital-twin.test.js
+++ b/server/services/digital-twin.test.js
@@ -105,6 +105,12 @@ import {
getTestHistory,
parseValuesAlignmentSuite,
getValuesAlignmentHistory,
+ getPersonas,
+ createPersona,
+ updatePersona,
+ deletePersona,
+ setActivePersona,
+ getActivePersona,
getEnrichmentCategories,
generateEnrichmentQuestion,
processEnrichmentAnswer,
@@ -141,6 +147,7 @@ const DEFAULT_META = {
documents: [],
testHistory: [],
valuesTestHistory: [],
+ personas: [],
enrichment: { completedCategories: [], lastSession: null },
settings: { autoInjectToCoS: true, maxContextTokens: 4000 }
};
@@ -148,6 +155,9 @@ const DEFAULT_META = {
const makeMeta = (overrides = {}) => ({
...DEFAULT_META,
...overrides,
+ // Fresh array so in-place mutation (e.g. createPersona's push) can't bleed
+ // across tests via the shared DEFAULT_META.personas reference.
+ personas: overrides.personas ? overrides.personas : [],
enrichment: { ...DEFAULT_META.enrichment, ...(overrides.enrichment || {}) },
settings: { ...DEFAULT_META.settings, ...(overrides.settings || {}) }
});
@@ -1176,6 +1186,109 @@ Quietly keeps the savings.
const lowIdx = result.indexOf('LOW_WEIGHT_CONTENT');
expect(highIdx).toBeLessThan(lowIdx);
});
+
+ it('prepends the active persona preamble when personaId is "active"', async () => {
+ const persona = {
+ id: 'p1', name: 'Professional', instructions: 'Be concise and formal.',
+ 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],
+ 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('Be concise and formal.');
+ expect(result).toContain('Soul content');
+ });
+
+ it('omits the persona preamble when no personaId is passed', async () => {
+ const persona = {
+ id: 'p1', name: 'Professional', instructions: 'Be concise and formal.',
+ 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],
+ 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();
+ expect(result).not.toContain('Active Persona');
+ expect(result).toContain('Soul content');
+ });
+ });
+
+ // ==========================================================================
+ // Personas (M34 P7)
+ // ==========================================================================
+
+ describe('personas', () => {
+ it('creates a persona with timestamps and lists it', async () => {
+ await setupMetaFile(makeMeta());
+ const persona = await createPersona({ name: 'Professional', description: 'Work voice', instructions: 'Be concise.' });
+ expect(persona.id).toBeTruthy();
+ expect(persona.name).toBe('Professional');
+ expect(persona.description).toBe('Work voice');
+ expect(persona.createdAt).toBeTruthy();
+ expect(persona.updatedAt).toBeTruthy();
+ expect(await getPersonas()).toHaveLength(1);
+ });
+
+ it('omits description when not provided', async () => {
+ await setupMetaFile(makeMeta());
+ const persona = await createPersona({ name: 'Casual', instructions: 'Relax.' });
+ expect(persona.description).toBeUndefined();
+ });
+
+ it('updates only the fields provided', async () => {
+ await setupMetaFile(makeMeta());
+ const persona = await createPersona({ name: 'A', instructions: 'one' });
+ const updated = await updatePersona(persona.id, { instructions: 'two' });
+ expect(updated.name).toBe('A');
+ expect(updated.instructions).toBe('two');
+ });
+
+ it('throws when updating a missing persona', async () => {
+ await setupMetaFile(makeMeta());
+ await expect(updatePersona('does-not-exist', { name: 'x' })).rejects.toThrow();
+ });
+
+ it('sets and reads back the active persona', async () => {
+ await setupMetaFile(makeMeta());
+ const persona = await createPersona({ name: 'A', instructions: 'one' });
+ await setActivePersona(persona.id);
+ const active = await getActivePersona();
+ expect(active.id).toBe(persona.id);
+ });
+
+ it('rejects activating a non-existent persona', async () => {
+ await setupMetaFile(makeMeta());
+ await expect(setActivePersona('missing')).rejects.toThrow();
+ });
+
+ it('clears the active pointer when the active persona is deleted', async () => {
+ await setupMetaFile(makeMeta());
+ const persona = await createPersona({ name: 'A', instructions: 'one' });
+ await setActivePersona(persona.id);
+ await deletePersona(persona.id);
+ expect(await getActivePersona()).toBeNull();
+ expect(await getPersonas()).toHaveLength(0);
+ });
});
// ==========================================================================