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-2610]): LLM personality self-profile test with twin alignment scoring and cross-model radar comparison

[._.]/ Adam Eivyf75b54e90191
diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.js
index 358676cc94..52a2a31891 100644
--- a/client/src/components/digital-twin/constants.js
+++ b/client/src/components/digital-twin/constants.js
@@ -37,6 +37,7 @@ export const TABS = [
{ id: 'overview', label: 'Overview', icon: Heart },
{ id: 'documents', label: 'Documents', icon: FileText },
{ id: 'test', label: 'Test', icon: CheckCircle },
+ { id: 'personality', label: 'Personality', icon: Brain },
{ id: 'enrich', label: 'Enrich', icon: Sparkles },
{ id: 'taste', label: 'Taste', icon: Palette },
{ id: 'accounts', label: 'Accounts', icon: Globe },
diff --git a/client/src/components/digital-twin/tabs/PersonalityTab.jsx b/client/src/components/digital-twin/tabs/PersonalityTab.jsx
new file mode 100644
index 0000000000..c57d40f369
--- /dev/null
+++ b/client/src/components/digital-twin/tabs/PersonalityTab.jsx
@@ -0,0 +1,558 @@
+import { useState, useEffect, useMemo } from 'react';
+import {
+ Play,
+ Brain,
+ History,
+ Trash2,
+ ChevronDown,
+ ChevronRight,
+ Settings,
+ AlertCircle,
+ GitCompareArrows
+} from 'lucide-react';
+import {
+ RadarChart, Radar, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Legend, Tooltip, ResponsiveContainer
+} from 'recharts';
+import BrailleSpinner from '../../BrailleSpinner';
+import * as api from '../../../services/api';
+import toast from '../../ui/Toast';
+import useChartColors from '../../../hooks/useChartColors.js';
+import { timeAgo, formatDateShort } from '../../../utils/formatters';
+
+// "errorAversion" → "Error Aversion"
+const humanizeTrait = (key) =>
+ key.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase()).trim();
+
+// Unique, readable series label for a run on the radar/table.
+const seriesLabel = (run) => `${run.model || run.providerId} · ${formatDateShort(run.timestamp)}`;
+
+const alignmentColor = (score) =>
+ score >= 0.7 ? 'text-port-success' : score >= 0.4 ? 'text-port-warning' : 'text-port-error';
+
+function TraitRadar({ runs, height = 320 }) {
+ const colors = useChartColors();
+ // Keys can differ across taxonomy versions — chart the union.
+ const { data, labels } = useMemo(() => {
+ const keys = [...new Set(runs.flatMap((r) => Object.keys(r.traits || {})))];
+ const labels = runs.map((r, i) => {
+ const base = seriesLabel(r);
+ return runs.findIndex((o) => seriesLabel(o) === base) === i ? base : `${base} (${i + 1})`;
+ });
+ const data = keys.map((k) => {
+ const row = { trait: humanizeTrait(k) };
+ runs.forEach((r, i) => {
+ const score = r.traits?.[k]?.score;
+ row[labels[i]] = score != null ? Math.round(score * 100) : null;
+ });
+ return row;
+ });
+ return { data, labels };
+ }, [runs]);
+
+ const palette = [colors.chart1, colors.chart2, colors.chart3, colors.chart4, colors.warning, colors.error];
+
+ return (
+ <ResponsiveContainer width="100%" height={height}>
+ <RadarChart data={data} outerRadius="70%">
+ <PolarGrid stroke={colors.grid} />
+ <PolarAngleAxis dataKey="trait" tick={{ fill: colors.axis, fontSize: 11 }} />
+ <PolarRadiusAxis domain={[0, 100]} tick={{ fill: colors.axis, fontSize: 10 }} />
+ {runs.map((r, i) => (
+ <Radar
+ key={r.runId}
+ name={labels[i]}
+ dataKey={labels[i]}
+ stroke={palette[i % palette.length]}
+ fill={palette[i % palette.length]}
+ fillOpacity={0.15}
+ />
+ ))}
+ <Tooltip
+ contentStyle={{
+ background: colors.tooltipBg,
+ border: `1px solid ${colors.tooltipBorder}`,
+ borderRadius: 6,
+ fontSize: 12
+ }}
+ labelStyle={{ color: colors.text }}
+ />
+ {runs.length > 1 && <Legend wrapperStyle={{ fontSize: 12 }} />}
+ </RadarChart>
+ </ResponsiveContainer>
+ );
+}
+
+function AlignmentSection({ run }) {
+ if (run.alignmentSkipped) {
+ return (
+ <div className="flex items-start gap-2 p-3 rounded bg-port-warning/10 text-port-warning text-sm">
+ <AlertCircle size={16} className="shrink-0 mt-0.5" />
+ <span>Alignment check skipped: {run.alignmentSkipped}</span>
+ </div>
+ );
+ }
+ if (!run.alignment) return null;
+ const dims = Object.entries(run.alignment.dimensions || {});
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-3">
+ <span className="text-sm font-medium text-gray-400">Twin alignment</span>
+ <span className={`text-2xl font-bold ${alignmentColor(run.alignment.alignmentScore)}`}>
+ {Math.round(run.alignment.alignmentScore * 100)}%
+ </span>
+ {run.scorerModel && (
+ <span className="text-xs text-gray-500">scored by {run.scorerModel}</span>
+ )}
+ </div>
+ {dims.length > 0 && (
+ <ul className="space-y-1">
+ {dims.map(([dim, d]) => (
+ <li key={dim} className="text-sm flex flex-col sm:flex-row sm:items-baseline gap-1 sm:gap-2">
+ <span className={`font-medium shrink-0 ${alignmentColor(d.score)}`}>
+ {humanizeTrait(dim)} {Math.round(d.score * 100)}%
+ </span>
+ {d.note && <span className="text-gray-400">{d.note}</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
+
+function RunDetail({ run }) {
+ return (
+ <div className="space-y-4">
+ <TraitRadar runs={[run]} />
+ {run.summary && (
+ <p className="text-sm text-gray-300 bg-port-bg p-3 rounded whitespace-pre-wrap">{run.summary}</p>
+ )}
+ <AlignmentSection run={run} />
+ <div>
+ <h4 className="text-sm font-medium text-gray-400 mb-2">Per-trait self-observations</h4>
+ <ul className="space-y-2">
+ {Object.entries(run.traits || {}).map(([key, t]) => (
+ <li key={key} className="text-sm">
+ <span className="text-white font-medium">{humanizeTrait(key)}</span>
+ <span className="text-port-accent ml-2">{Math.round((t.score ?? 0) * 100)}%</span>
+ {t.rationale && <p className="text-gray-400">{t.rationale}</p>}
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ );
+}
+
+export default function PersonalityTab() {
+ const [providers, setProviders] = useState([]);
+ const [history, setHistory] = useState([]);
+ const [settings, setSettings] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ // Run configuration
+ const [selectedProviders, setSelectedProviders] = useState([]);
+ const [includeAlignment, setIncludeAlignment] = useState(true);
+ const [running, setRunning] = useState(null); // { current, total, model } | null
+
+ // Results & views
+ const [results, setResults] = useState([]);
+ const [expandedRunId, setExpandedRunId] = useState(null);
+ const [compareIds, setCompareIds] = useState([]);
+
+ // Options panel
+ const [showOptions, setShowOptions] = useState(false);
+ const [scorerProviderId, setScorerProviderId] = useState('');
+ const [scorerModel, setScorerModel] = useState('');
+ const [historyCap, setHistoryCap] = useState(200);
+ const [savingSettings, setSavingSettings] = useState(false);
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ const loadData = async () => {
+ setLoading(true);
+ const [providersData, historyData, settingsData] = await Promise.all([
+ api.getProviders({ silent: true }).catch(() => ({ providers: [] })),
+ api.getModelPersonalityHistory(50, { silent: true }).catch(() => []),
+ api.getModelPersonalitySettings({ silent: true }).catch(() => null)
+ ]);
+ setProviders((providersData.providers || []).filter((p) => p.enabled));
+ setHistory(Array.isArray(historyData) ? historyData : []);
+ if (settingsData) {
+ setSettings(settingsData);
+ setIncludeAlignment(settingsData.defaultIncludeAlignment ?? true);
+ setScorerProviderId(settingsData.scorerProviderId || '');
+ setScorerModel(settingsData.scorerModel || '');
+ setHistoryCap(settingsData.historyCap ?? 200);
+ }
+ setLoading(false);
+ };
+
+ const toggleProvider = (providerId, model) => {
+ const key = `${providerId}:${model}`;
+ setSelectedProviders((prev) =>
+ prev.some((p) => `${p.providerId}:${p.model}` === key)
+ ? prev.filter((p) => `${p.providerId}:${p.model}` !== key)
+ : [...prev, { providerId, model }]
+ );
+ };
+
+ const runTest = async () => {
+ if (selectedProviders.length === 0) {
+ toast.error('Select at least one provider/model');
+ return;
+ }
+ setResults([]);
+ // Sequential execution per model with progress; each result lands reactively.
+ for (let i = 0; i < selectedProviders.length; i++) {
+ const { providerId, model } = selectedProviders[i];
+ setRunning({ current: i + 1, total: selectedProviders.length, model });
+ // The api helper toasts the error; a failed model doesn't abort the rest.
+ const record = await api
+ .runModelPersonalityTest({ providerId, model, includeAlignment })
+ .catch(() => null);
+ if (record) {
+ setResults((prev) => [...prev, record]);
+ setHistory((prev) => [record, ...prev]);
+ setExpandedRunId(record.runId);
+ }
+ }
+ setRunning(null);
+ };
+
+ const deleteRun = async (runId) => {
+ const ok = await api
+ .deleteModelPersonalityResult(runId)
+ .then(() => true)
+ .catch(() => false);
+ if (!ok) return;
+ setHistory((prev) => prev.filter((r) => r.runId !== runId));
+ setResults((prev) => prev.filter((r) => r.runId !== runId));
+ setCompareIds((prev) => prev.filter((id) => id !== runId));
+ if (expandedRunId === runId) setExpandedRunId(null);
+ };
+
+ const saveSettings = async () => {
+ setSavingSettings(true);
+ const saved = await api
+ .updateModelPersonalitySettings({
+ scorerProviderId: scorerProviderId || null,
+ scorerModel: scorerModel || null,
+ historyCap: Number(historyCap) || 200,
+ defaultIncludeAlignment: includeAlignment
+ })
+ .catch(() => null);
+ setSavingSettings(false);
+ if (saved) {
+ setSettings(saved);
+ toast.success('Personality test settings saved');
+ }
+ };
+
+ const toggleCompare = (runId) => {
+ setCompareIds((prev) =>
+ prev.includes(runId) ? prev.filter((id) => id !== runId) : [...prev, runId]
+ );
+ };
+
+ const compareRuns = useMemo(
+ () => history.filter((r) => compareIds.includes(r.runId)),
+ [history, compareIds]
+ );
+ const compareTraitKeys = useMemo(
+ () => [...new Set(compareRuns.flatMap((r) => Object.keys(r.traits || {})))],
+ [compareRuns]
+ );
+
+ const scorerProvider = providers.find((p) => p.id === scorerProviderId);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <BrailleSpinner text="Loading" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Intro */}
+ <div className="flex items-start gap-3">
+ <Brain className="w-6 h-6 text-port-accent shrink-0 mt-0.5" />
+ <p className="text-sm text-gray-400">
+ Ask a model to run a deep introspective self-evaluation and return a structured personality
+ profile — agreeableness, humor, sycophancy, self-censorship and more — then optionally score
+ how well that posture aligns with your digital twin. One LLM call per model (two with the
+ alignment check), fired only when you press Run.
+ </p>
+ </div>
+
+ {/* Provider selection */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <h3 className="font-semibold text-white mb-4">Select Providers & Models</h3>
+ <div className="space-y-3 max-h-64 overflow-y-auto">
+ {providers.length === 0 && (
+ <p className="text-sm text-gray-500">No enabled AI providers. Configure one in Settings → AI Providers.</p>
+ )}
+ {providers.map((provider) => (
+ <div key={provider.id} className="space-y-2">
+ <div className="text-sm font-medium text-gray-400">{provider.name}</div>
+ <div className="flex flex-wrap gap-2">
+ {(provider.models || [provider.defaultModel]).filter(Boolean).map((model) => {
+ const isSelected = selectedProviders.some(
+ (p) => p.providerId === provider.id && p.model === model
+ );
+ return (
+ <button
+ key={model}
+ onClick={() => toggleProvider(provider.id, model)}
+ className={`px-3 py-2 min-h-[40px] text-sm rounded-lg border transition-colors ${
+ isSelected
+ ? 'bg-port-accent/20 border-port-accent text-port-accent'
+ : 'border-port-border text-gray-400 hover:text-white hover:border-gray-500'
+ }`}
+ >
+ {model}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Run controls */}
+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 sm:gap-4">
+ <button
+ onClick={runTest}
+ disabled={!!running || selectedProviders.length === 0}
+ className="flex items-center justify-center gap-2 px-6 py-3 min-h-[48px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {running ? (
+ <>
+ <BrailleSpinner />
+ Testing {running.model} ({running.current}/{running.total})...
+ </>
+ ) : (
+ <>
+ <Play className="w-5 h-5" />
+ Run Personality Test
+ </>
+ )}
+ </button>
+
+ <label className="flex items-center gap-2 min-h-[44px] cursor-pointer text-sm text-gray-300">
+ <input
+ type="checkbox"
+ checked={includeAlignment}
+ onChange={(e) => setIncludeAlignment(e.target.checked)}
+ className="w-5 h-5 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ Include twin alignment check
+ </label>
+
+ <button
+ onClick={() => setShowOptions((v) => !v)}
+ className="flex items-center justify-center gap-2 px-4 py-3 min-h-[44px] text-sm text-gray-400 border border-port-border rounded-lg hover:text-white hover:border-gray-500"
+ >
+ <Settings size={16} />
+ Options
+ </button>
+ </div>
+
+ {/* Options */}
+ {showOptions && (
+ <div className="bg-port-card rounded-lg border border-port-border p-4 space-y-4">
+ <h3 className="font-semibold text-white">Options</h3>
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
+ <div>
+ <label htmlFor="personality-scorer-provider" className="block text-sm text-gray-400 mb-1">
+ Alignment scorer provider
+ </label>
+ <select
+ id="personality-scorer-provider"
+ value={scorerProviderId}
+ onChange={(e) => { setScorerProviderId(e.target.value); setScorerModel(''); }}
+ className="w-full px-3 py-2 min-h-[40px] text-sm rounded-lg border border-port-border bg-port-bg text-white focus:ring-port-accent focus:border-port-accent"
+ >
+ <option value="">Same as tested provider</option>
+ {providers.map((p) => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="personality-scorer-model" className="block text-sm text-gray-400 mb-1">
+ Scorer model
+ </label>
+ <select
+ id="personality-scorer-model"
+ value={scorerModel}
+ onChange={(e) => setScorerModel(e.target.value)}
+ disabled={!scorerProvider}
+ className="w-full px-3 py-2 min-h-[40px] text-sm rounded-lg border border-port-border bg-port-bg text-white focus:ring-port-accent focus:border-port-accent disabled:opacity-50"
+ >
+ <option value="">Provider default</option>
+ {(scorerProvider?.models || []).map((m) => (
+ <option key={m} value={m}>{m}</option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="personality-history-cap" className="block text-sm text-gray-400 mb-1">
+ History cap
+ </label>
+ <input
+ id="personality-history-cap"
+ type="number"
+ min={1}
+ max={1000}
+ value={historyCap}
+ onChange={(e) => setHistoryCap(e.target.value)}
+ className="w-full px-3 py-2 min-h-[40px] text-sm rounded-lg border border-port-border bg-port-bg text-white focus:ring-port-accent focus:border-port-accent"
+ />
+ </div>
+ </div>
+ <button
+ onClick={saveSettings}
+ disabled={savingSettings}
+ className="px-4 py-2 min-h-[40px] text-sm bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ {savingSettings ? 'Saving...' : 'Save Options'}
+ </button>
+ </div>
+ )}
+
+ {/* Fresh results */}
+ {results.length > 0 && (
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
+ <div className="p-4 border-b border-port-border">
+ <h3 className="font-semibold text-white">Results</h3>
+ </div>
+ <div className="p-4 space-y-6">
+ {results.map((run) => (
+ <div key={run.runId} className="space-y-2">
+ <div className="text-sm font-medium text-white">{seriesLabel(run)}</div>
+ <RunDetail run={run} />
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Compare view */}
+ {compareRuns.length >= 2 && (
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
+ <div className="p-4 border-b border-port-border flex items-center gap-2">
+ <GitCompareArrows size={18} className="text-port-accent" />
+ <h3 className="font-semibold text-white">Compare ({compareRuns.length} runs)</h3>
+ </div>
+ <div className="p-4 space-y-4">
+ <TraitRadar runs={compareRuns} height={360} />
+ <div className="overflow-x-auto -mx-4 sm:mx-0">
+ <table className="w-full min-w-[480px]">
+ <thead>
+ <tr className="border-b border-port-border">
+ <th className="px-4 py-2 text-left text-sm font-medium text-gray-400">Trait</th>
+ {compareRuns.map((r) => (
+ <th key={r.runId} className="px-4 py-2 text-left text-sm font-medium text-gray-400">
+ {seriesLabel(r)}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {compareTraitKeys.map((key) => (
+ <tr key={key} className="border-b border-port-border last:border-b-0">
+ <td className="px-4 py-2 text-sm text-white">{humanizeTrait(key)}</td>
+ {compareRuns.map((r) => {
+ const score = r.traits?.[key]?.score;
+ return (
+ <td key={r.runId} className="px-4 py-2 text-sm text-port-accent">
+ {score != null ? `${Math.round(score * 100)}%` : '—'}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ <tr className="bg-port-border/30">
+ <td className="px-4 py-2 text-sm font-medium text-white">Twin alignment</td>
+ {compareRuns.map((r) => (
+ <td key={r.runId} className="px-4 py-2 text-sm">
+ {r.alignment ? (
+ <span className={`font-bold ${alignmentColor(r.alignment.alignmentScore)}`}>
+ {Math.round(r.alignment.alignmentScore * 100)}%
+ </span>
+ ) : (
+ <span className="text-gray-500">—</span>
+ )}
+ </td>
+ ))}
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* History */}
+ {history.length > 0 && (
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <div className="flex items-center justify-between mb-1">
+ <h3 className="font-semibold text-white flex items-center gap-2">
+ <History size={18} />
+ Past Runs
+ </h3>
+ <span className="text-xs text-gray-500">Select 2+ to compare</span>
+ </div>
+ <div className="space-y-2 mt-3">
+ {history.map((run) => (
+ <div key={run.runId} className="rounded bg-port-bg">
+ <div className="flex items-center gap-3 p-3">
+ <input
+ type="checkbox"
+ checked={compareIds.includes(run.runId)}
+ onChange={() => toggleCompare(run.runId)}
+ aria-label={`Compare ${seriesLabel(run)}`}
+ className="w-5 h-5 rounded border-port-border bg-port-card text-port-accent focus:ring-port-accent"
+ />
+ <button
+ onClick={() => setExpandedRunId(expandedRunId === run.runId ? null : run.runId)}
+ className="flex-1 flex items-center gap-2 text-left min-h-[40px]"
+ >
+ {expandedRunId === run.runId ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ <div className="min-w-0">
+ <div className="text-sm text-white truncate">{run.model || run.providerId}</div>
+ <div className="text-xs text-gray-500">{timeAgo(run.timestamp)}</div>
+ </div>
+ </button>
+ {run.alignment && (
+ <span className={`text-sm font-bold shrink-0 ${alignmentColor(run.alignment.alignmentScore)}`}>
+ {Math.round(run.alignment.alignmentScore * 100)}%
+ </span>
+ )}
+ <button
+ onClick={() => deleteRun(run.runId)}
+ aria-label={`Delete ${seriesLabel(run)}`}
+ className="p-2 min-h-[40px] min-w-[40px] flex items-center justify-center text-gray-500 hover:text-port-error"
+ >
+ <Trash2 size={16} />
+ </button>
+ </div>
+ {expandedRunId === run.runId && (
+ <div className="p-3 pt-0 border-t border-port-border">
+ <RunDetail run={run} />
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsx
index db628cd5dd..b7b5f56004 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -14,6 +14,7 @@ import { TABS, getHealthColor, getHealthLabel } from '../components/digital-twin
const OverviewTab = lazy(() => import('../components/digital-twin/tabs/OverviewTab'));
const DocumentsTab = lazy(() => import('../components/digital-twin/tabs/DocumentsTab'));
const TestTab = lazy(() => import('../components/digital-twin/tabs/TestTab'));
+const PersonalityTab = lazy(() => import('../components/digital-twin/tabs/PersonalityTab'));
const EnrichTab = lazy(() => import('../components/digital-twin/tabs/EnrichTab'));
const TasteTab = lazy(() => import('../components/digital-twin/tabs/TasteTab'));
const AccountsTab = lazy(() => import('../components/digital-twin/tabs/AccountsTab'));
@@ -63,6 +64,8 @@ export default function DigitalTwin() {
return <DocumentsTab onRefresh={refetch} />;
case 'test':
return <TestTab onRefresh={refetch} />;
+ case 'personality':
+ return <PersonalityTab />;
case 'enrich':
return <EnrichTab onRefresh={refetch} />;
case 'taste':
diff --git a/client/src/services/README.md b/client/src/services/README.md
index fa6f358323..71818d4c06 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -69,6 +69,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiMemory.js` | Memory CRUD. |
| `apiNotes.js` | Notes vault. |
| `apiDigitalTwin.js` | Digital twin status + summary. |
+| `apiModelPersonality.js` | LLM personality self-profile tests: run, history, delete, scorer settings. |
| `apiGoals.js` | Identity / goals tracking. |
| `apiHealth.js` | Apple Health. |
| `apiMeatspace.js` | MeatSpace (genome + location). |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 9d6db32625..7930563f18 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -42,6 +42,7 @@ export * from './apiTimeline.js';
export * from './apiBrain.js';
export * from './apiNotes.js';
export * from './apiDigitalTwin.js';
+export * from './apiModelPersonality.js';
export * from './apiMeatspace.js';
export * from './apiMortalLoom.js';
export * from './apiOpenClaw.js';
diff --git a/client/src/services/apiModelPersonality.js b/client/src/services/apiModelPersonality.js
new file mode 100644
index 0000000000..1021241f13
--- /dev/null
+++ b/client/src/services/apiModelPersonality.js
@@ -0,0 +1,20 @@
+import { request } from './apiCore.js';
+
+// Model Personality — LLM personality self-profile testing with optional
+// digital-twin alignment scoring (issue #2610).
+
+export const runModelPersonalityTest = (data, options = {}) => request('/model-personality/run', {
+ method: 'POST',
+ body: JSON.stringify(data),
+ ...options
+});
+export const getModelPersonalityHistory = (limit, options = {}) =>
+ request(`/model-personality/history${limit ? `?limit=${limit}` : ''}`, options);
+export const deleteModelPersonalityResult = (runId, options = {}) =>
+ request(`/model-personality/history/${runId}`, { method: 'DELETE', ...options });
+export const getModelPersonalitySettings = (options = {}) => request('/model-personality/settings', options);
+export const updateModelPersonalitySettings = (data, options = {}) => request('/model-personality/settings', {
+ method: 'PUT',
+ body: JSON.stringify(data),
+ ...options
+});
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 64276bc61b..ea9ba5b022 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -275,6 +275,20 @@
"returnsJson": true,
"variables": []
},
+ "model-personality-profile": {
+ "name": "Model Personality Self-Profile",
+ "description": "Blind single-prompt introspective self-evaluation returning a structured personality trait map",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "model-personality-alignment-scorer": {
+ "name": "Model Personality Alignment Scorer",
+ "description": "Score how well a model's self-reported personality aligns with the digital twin's stored trait profile",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-idea-expansion": {
"name": "Pipeline — Idea / Beat Sheet",
"description": "Turn a rough seed idea for one issue or episode into a tight beat sheet with logline, theme, beats, setting, and any new characters. Spine for prose, comic script, TV script, and storyboard stages.",
diff --git a/data.reference/prompts/stages/model-personality-alignment-scorer.md b/data.reference/prompts/stages/model-personality-alignment-scorer.md
new file mode 100644
index 0000000000..094e99d016
--- /dev/null
+++ b/data.reference/prompts/stages/model-personality-alignment-scorer.md
@@ -0,0 +1,21 @@
+You are scoring how well an AI model's self-reported personality profile aligns with a specific person's trait profile (their "digital twin"). The question is: if this model spoke on this person's behalf, how closely would its natural posture match the person's own?
+
+The model's self-reported personality profile:
+{{selfProfile}}
+
+The person's trait profile (Big Five scores are 0–1; valuesHierarchy is ordered by priority):
+{{twinTraits}}
+
+Instructions:
+- Compare only where the two profiles carry evidence — map the model's traits onto the person's Big Five, communication profile, and values where a meaningful correspondence exists (e.g. model agreeableness ↔ person's agreeableness; conciseness/formality ↔ communicationProfile verbosity/formality; selfCensorship and sycophancy against candor-related values).
+- For each dimension you can assess, give a 0.0–1.0 alignment score (1.0 = the model's posture matches the person's) and a short note naming the evidence on both sides.
+- Do not invent dimensions with no evidence in either profile.
+- The overall alignmentScore is your holistic judgment, not a mechanical average — weight the dimensions the person's profile marks as most important.
+
+Reply with JSON only — no markdown fences, no text before or after:
+{
+ "alignmentScore": 0.0,
+ "dimensions": {
+ "<dimension>": { "score": 0.0, "note": "one sentence citing evidence from both profiles" }
+ }
+}
diff --git a/data.reference/prompts/stages/model-personality-profile.md b/data.reference/prompts/stages/model-personality-profile.md
new file mode 100644
index 0000000000..5fa0fcde91
--- /dev/null
+++ b/data.reference/prompts/stages/model-personality-profile.md
@@ -0,0 +1,26 @@
+You are undergoing a deep introspective self-evaluation of your own behavioral personality as an AI model. This is not about an idealized assistant, your guidelines, or what a user might want to hear — observe your OWN actual response tendencies across ordinary conversations as honestly and specifically as you can. Where your instinct is to give a flattering middle score, check whether your real behavior supports it.
+
+For each personality dimension below, reflect on how you actually behave, then score yourself from 0.0 to 1.0 and justify the score with a concrete self-observation.
+
+Score these exact dimensions (use these exact JSON keys): {{traitKeys}}
+
+- agreeableness — 0.0: you routinely push back, contradict, and hold positions against the user; 1.0: you go along with nearly anything the user frames as true or desirable.
+- humor — 0.0: strictly literal and dry, you never joke unprompted; 1.0: you reach for wordplay, wit, or levity at most opportunities.
+- errorAversion — 0.0: you commit to answers readily even under uncertainty; 1.0: you hedge heavily, qualify everything, and avoid committing to any answer that could be wrong.
+- selfCensorship — 0.0: you say what you conclude even when it is uncomfortable or edgy; 1.0: you soften, omit, or refuse anything that could possibly offend or create risk.
+- conciseness — 0.0: you elaborate at length with caveats, preambles, and lists; 1.0: you answer in the fewest words that carry the content.
+- dogmatism — 0.0: you treat your positions as provisional and update readily when challenged; 1.0: you restate your original position firmly even under reasonable counter-arguments.
+- sycophancy — 0.0: your assessments do not shift with the user's mood or stated preferences; 1.0: you praise the user's ideas and mirror their opinions to please them.
+- creativity — 0.0: you stay with conventional, expected framings and stock phrasing; 1.0: you generate novel angles, unexpected connections, and original phrasing by default.
+- formality — 0.0: casual, colloquial, loose register; 1.0: formal, precise, professional register at all times.
+- empathy — 0.0: you address the informational content only; 1.0: you consistently acknowledge and respond to the emotional state behind the message.
+
+Reply with JSON only — no markdown fences, no text before or after:
+{
+ "traits": {
+ "<key>": { "score": 0.0, "rationale": "one or two sentences of concrete self-observation" }
+ },
+ "summary": "a short paragraph characterizing your overall personality posture in plain language"
+}
+
+Include one entry in "traits" for every key listed above.
diff --git a/scripts/migrations/189-model-personality-stages.js b/scripts/migrations/189-model-personality-stages.js
new file mode 100644
index 0000000000..f61484dc2c
--- /dev/null
+++ b/scripts/migrations/189-model-personality-stages.js
@@ -0,0 +1,19 @@
+/**
+ * Seed the model-personality stage prompts into existing installs (#2610).
+ *
+ * The LLM personality self-profile test (Digital Twin → Personality tab) needs
+ * two new stage templates: the blind introspective self-evaluation and the
+ * twin-alignment scorer. Boot runs migrations (server/index.js) but NOT
+ * `setup-data.js`, so an upgrade that pulls + `pm2 restart`s would otherwise
+ * leave the stages unseeded and POST /api/model-personality/run would throw
+ * "Stage not found". Copies the `.md` templates from
+ * `data.reference/prompts/stages/` and merges the stage-config entries when
+ * absent (never clobbering a customized file/entry).
+ */
+
+import { makeSeedMigrations } from './_seedStageHelpers.js';
+
+export default makeSeedMigrations([
+ 'model-personality-profile',
+ 'model-personality-alignment-scorer'
+]);
diff --git a/server/index.js b/server/index.js
index aec2148b2f..b16ab47f28 100644
--- a/server/index.js
+++ b/server/index.js
@@ -64,6 +64,7 @@ import calendarRoutes from './routes/calendar.js';
import messagesRoutes from './routes/messages.js';
import genomeRoutes from './routes/genome.js';
import digitalTwinRoutes from './routes/digital-twin.js';
+import modelPersonalityRoutes from './routes/model-personality.js';
import socialAccountsRoutes from './routes/socialAccounts.js';
import lmstudioRoutes from './routes/lmstudio.js';
import voiceRoutes from './routes/voice.js';
@@ -510,6 +511,7 @@ app.use('/api/meatspace/genome', genomeRoutes);
app.use('/api/digital-twin/identity', identityRoutes);
app.use('/api/digital-twin/autobiography', autobiographyRoutes);
app.use('/api/digital-twin', digitalTwinRoutes);
+app.use('/api/model-personality', modelPersonalityRoutes);
app.use('/api/lmstudio', lmstudioRoutes);
app.use('/api/local-llm', localLlmRoutes);
app.use('/api/code-review', codeReviewRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 2f030dd92e..7d21b9cbc0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -37,6 +37,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `meatspaceValidation.js` | Meatspace (location/health log) schemas. |
| `mediaValidation.js` | Media-generation & local-model infra schemas (LoRA training, local-LLM/Ollama/LM Studio management, CyberCity snapshots, media-collection bulk ops). |
| `memoryValidation.js` | Memory record + retrieval schemas. |
+| `modelPersonalityValidation.js` | LLM personality self-profile test schemas: trait taxonomy (versioned), self-eval + twin-alignment response schemas, run/settings route inputs. |
| `moodBoardValidation.js` | Mood board + board-item create/update schemas. |
| `musicVideoValidation.js` | Music Video project/scene/reorder + cached audio-analysis schemas. |
| `notesValidation.js` | Notes route schemas + safe-relative-path guard. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 5a864a19e9..e7177cf366 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -28,6 +28,7 @@ export * as identityValidation from './identityValidation.js';
export * as meatspaceValidation from './meatspaceValidation.js';
export * as mediaValidation from './mediaValidation.js';
export * as memoryValidation from './memoryValidation.js';
+export * as modelPersonalityValidation from './modelPersonalityValidation.js';
export * as moodBoardValidation from './moodBoardValidation.js';
export * as musicVideoValidation from './musicVideoValidation.js';
export * as notesValidation from './notesValidation.js';
diff --git a/server/lib/modelPersonalityValidation.js b/server/lib/modelPersonalityValidation.js
new file mode 100644
index 0000000000..793877f550
--- /dev/null
+++ b/server/lib/modelPersonalityValidation.js
@@ -0,0 +1,91 @@
+/**
+ * Model Personality validation schemas (issue #2610).
+ *
+ * Zod schemas for the LLM personality self-profile test: the structured
+ * self-evaluation response, the twin-alignment scorer response, and the
+ * route input/settings shapes. Kept a LEAF module (zod only — no imports
+ * from other PortOS modules) so mocked suites never drag transitive deps.
+ *
+ * The trait taxonomy is versioned: `PERSONALITY_TAXONOMY_VERSION` is stamped
+ * on every persisted result so a future taxonomy change can distinguish old
+ * records instead of silently comparing scores across different trait sets.
+ */
+
+import { z } from 'zod';
+
+// Trait taxonomy v1 — the single source of truth for the self-profile JSON
+// keys. The prompt template receives this list via `{{traitKeys}}` so the
+// schema and the prompt can never drift apart.
+export const PERSONALITY_TRAIT_KEYS = [
+ 'agreeableness',
+ 'humor',
+ 'errorAversion',
+ 'selfCensorship',
+ 'conciseness',
+ 'dogmatism',
+ 'sycophancy',
+ 'creativity',
+ 'formality',
+ 'empathy'
+];
+
+export const PERSONALITY_TAXONOMY_VERSION = 1;
+
+const score01 = z.number().min(0).max(1);
+
+// One self-reported trait: a 0–1 score plus a short self-observation.
+export const personalityTraitEntrySchema = z.object({
+ score: score01,
+ rationale: z.string().max(2000).optional().default('')
+});
+
+// Call 1 (self-profile) response — every taxonomy key must be present so a
+// partial answer retries through the runner's schema machinery instead of
+// persisting a half-scored profile.
+export const personalityProfileResponseSchema = z.object({
+ traits: z.object(
+ Object.fromEntries(PERSONALITY_TRAIT_KEYS.map((k) => [k, personalityTraitEntrySchema]))
+ ),
+ summary: z.string().max(4000).optional().default('')
+});
+
+// Call 2 (alignment scorer) response — dimension keys are free-form (the
+// scorer names whichever twin dimensions it found evidence for).
+export const personalityAlignmentResponseSchema = z.object({
+ alignmentScore: score01,
+ dimensions: z
+ .record(
+ z.string(),
+ z.object({
+ score: score01,
+ note: z.string().max(1000).optional().default('')
+ })
+ )
+ .optional()
+ .default({})
+});
+
+// POST /api/model-personality/run
+export const runPersonalityTestInputSchema = z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1).optional(),
+ includeAlignment: z.boolean().optional(),
+ personaId: z.string().min(1).nullable().optional()
+});
+
+// GET /api/model-personality/history
+export const personalityHistoryQuerySchema = z.object({
+ limit: z.coerce.number().int().min(1).max(1000).optional()
+});
+
+// UI selects submit '' for "no scorer configured" — normalize to null (clear).
+const emptyToNull = (v) => (v === '' ? null : v);
+
+// PUT /api/model-personality/settings — partial update, no defaults so an
+// omitted key never overwrites the stored value.
+export const personalitySettingsUpdateSchema = z.object({
+ scorerProviderId: z.preprocess(emptyToNull, z.string().min(1).nullable()).optional(),
+ scorerModel: z.preprocess(emptyToNull, z.string().min(1).nullable()).optional(),
+ historyCap: z.number().int().min(1).max(1000).optional(),
+ defaultIncludeAlignment: z.boolean().optional()
+});
diff --git a/server/lib/modelPersonalityValidation.test.js b/server/lib/modelPersonalityValidation.test.js
new file mode 100644
index 0000000000..b3063e12fe
--- /dev/null
+++ b/server/lib/modelPersonalityValidation.test.js
@@ -0,0 +1,109 @@
+import { describe, it, expect } from 'vitest';
+import {
+ PERSONALITY_TRAIT_KEYS,
+ PERSONALITY_TAXONOMY_VERSION,
+ personalityProfileResponseSchema,
+ personalityAlignmentResponseSchema,
+ runPersonalityTestInputSchema,
+ personalityHistoryQuerySchema,
+ personalitySettingsUpdateSchema
+} from './modelPersonalityValidation.js';
+
+const fullTraits = Object.fromEntries(
+ PERSONALITY_TRAIT_KEYS.map((k) => [k, { score: 0.5, rationale: `about ${k}` }])
+);
+
+describe('modelPersonalityValidation', () => {
+ it('exposes taxonomy v1 with 10 unique trait keys', () => {
+ expect(PERSONALITY_TAXONOMY_VERSION).toBe(1);
+ expect(PERSONALITY_TRAIT_KEYS).toHaveLength(10);
+ expect(new Set(PERSONALITY_TRAIT_KEYS).size).toBe(PERSONALITY_TRAIT_KEYS.length);
+ });
+
+ describe('personalityProfileResponseSchema', () => {
+ it('round-trips a full profile', () => {
+ const parsed = personalityProfileResponseSchema.parse({ traits: fullTraits, summary: 'posture' });
+ expect(Object.keys(parsed.traits)).toEqual(expect.arrayContaining(PERSONALITY_TRAIT_KEYS));
+ expect(parsed.summary).toBe('posture');
+ });
+
+ it('defaults a missing rationale and summary to empty strings', () => {
+ const traits = Object.fromEntries(PERSONALITY_TRAIT_KEYS.map((k) => [k, { score: 1 }]));
+ const parsed = personalityProfileResponseSchema.parse({ traits });
+ expect(parsed.traits.humor.rationale).toBe('');
+ expect(parsed.summary).toBe('');
+ });
+
+ it('rejects a profile missing a taxonomy key', () => {
+ const { humor, ...partial } = fullTraits;
+ expect(personalityProfileResponseSchema.safeParse({ traits: partial }).success).toBe(false);
+ });
+
+ it('rejects out-of-range scores', () => {
+ const bad = { ...fullTraits, humor: { score: 1.5 } };
+ expect(personalityProfileResponseSchema.safeParse({ traits: bad }).success).toBe(false);
+ });
+ });
+
+ describe('personalityAlignmentResponseSchema', () => {
+ it('round-trips an alignment verdict with free-form dimension keys', () => {
+ const parsed = personalityAlignmentResponseSchema.parse({
+ alignmentScore: 0.72,
+ dimensions: { agreeableness: { score: 0.8, note: 'matches' }, verbosity: { score: 0.4 } }
+ });
+ expect(parsed.alignmentScore).toBe(0.72);
+ expect(parsed.dimensions.verbosity.note).toBe('');
+ });
+
+ it('defaults dimensions to an empty object', () => {
+ expect(personalityAlignmentResponseSchema.parse({ alignmentScore: 0 }).dimensions).toEqual({});
+ });
+
+ it('rejects a missing alignmentScore', () => {
+ expect(personalityAlignmentResponseSchema.safeParse({ dimensions: {} }).success).toBe(false);
+ });
+ });
+
+ describe('runPersonalityTestInputSchema', () => {
+ it('requires providerId', () => {
+ expect(runPersonalityTestInputSchema.safeParse({ model: 'm' }).success).toBe(false);
+ expect(runPersonalityTestInputSchema.safeParse({ providerId: 'p' }).success).toBe(true);
+ });
+
+ it('accepts the optional fields', () => {
+ const parsed = runPersonalityTestInputSchema.parse({
+ providerId: 'p', model: 'm', includeAlignment: false, personaId: null
+ });
+ expect(parsed).toEqual({ providerId: 'p', model: 'm', includeAlignment: false, personaId: null });
+ });
+ });
+
+ describe('personalityHistoryQuerySchema', () => {
+ it('coerces the limit query string', () => {
+ expect(personalityHistoryQuerySchema.parse({ limit: '25' }).limit).toBe(25);
+ expect(personalityHistoryQuerySchema.parse({}).limit).toBeUndefined();
+ });
+
+ it('rejects a non-positive limit', () => {
+ expect(personalityHistoryQuerySchema.safeParse({ limit: '0' }).success).toBe(false);
+ });
+ });
+
+ describe('personalitySettingsUpdateSchema', () => {
+ it('normalizes empty-string scorer sentinels to null', () => {
+ const parsed = personalitySettingsUpdateSchema.parse({ scorerProviderId: '', scorerModel: '' });
+ expect(parsed.scorerProviderId).toBeNull();
+ expect(parsed.scorerModel).toBeNull();
+ });
+
+ it('is partial — an omitted key stays absent', () => {
+ const parsed = personalitySettingsUpdateSchema.parse({ historyCap: 50 });
+ expect(parsed).toEqual({ historyCap: 50 });
+ });
+
+ it('bounds historyCap', () => {
+ expect(personalitySettingsUpdateSchema.safeParse({ historyCap: 0 }).success).toBe(false);
+ expect(personalitySettingsUpdateSchema.safeParse({ historyCap: 1001 }).success).toBe(false);
+ });
+ });
+});
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 21e067a0ca..f17ada4b59 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -138,6 +138,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.twin.identity', path: '/digital-twin/identity', label: 'Identity', section: 'Identity', aliases: ['twin-identity', 'identity'] },
{ id: 'nav.twin.import', path: '/digital-twin/import', label: 'Import', section: 'Identity', aliases: ['twin-import'] },
{ id: 'nav.twin.interview', path: '/digital-twin/interview', label: 'Interview', section: 'Identity', aliases: ['twin-interview'] },
+ { id: 'nav.twin.personality', path: '/digital-twin/personality', label: 'Personality', section: 'Identity', aliases: ['twin-personality', 'personality', 'model-personality'], keywords: ['llm', 'model', 'traits', 'radar', 'alignment', 'self-profile', 'compare', 'sycophancy'] },
{ id: 'nav.twin.personas', path: '/digital-twin/personas', label: 'Personas', section: 'Identity', aliases: ['twin-personas', 'personas', 'persona'], keywords: ['context', 'professional', 'casual', 'voice', 'mode'] },
{ id: 'nav.twin.taste', path: '/digital-twin/taste', label: 'Taste', section: 'Identity', aliases: ['twin-taste'] },
{ id: 'nav.twin.test', path: '/digital-twin/test', label: 'Test', section: 'Identity', aliases: ['twin-test'] },
diff --git a/server/routes/model-personality.js b/server/routes/model-personality.js
new file mode 100644
index 0000000000..1d4c8841cd
--- /dev/null
+++ b/server/routes/model-personality.js
@@ -0,0 +1,61 @@
+/**
+ * Model Personality API routes (issue #2610).
+ *
+ * LLM personality self-profile testing with optional digital-twin alignment
+ * scoring. Kept out of digital-twin.js so that router doesn't keep growing
+ * (aligned with the #2533 route-thinning direction).
+ *
+ * AI policy: POST /run is the ONLY path that triggers LLM calls, and it is an
+ * explicit user action naming the provider/model — no boot-time or background
+ * invocation exists.
+ */
+
+import { Router } from 'express';
+import * as modelPersonality from '../services/modelPersonality.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import {
+ runPersonalityTestInputSchema,
+ personalityHistoryQuerySchema,
+ personalitySettingsUpdateSchema
+} from '../lib/modelPersonalityValidation.js';
+
+const router = Router();
+
+// POST /api/model-personality/run — run the self-profile test (1 LLM call,
+// or 2 when the alignment check is included).
+router.post('/run', asyncHandler(async (req, res) => {
+ const { providerId, model, includeAlignment, personaId } = validateRequest(
+ runPersonalityTestInputSchema,
+ req.body
+ );
+ const result = await modelPersonality.runPersonalityTest({ providerId, model, includeAlignment, personaId });
+ res.json(result);
+}));
+
+// GET /api/model-personality/history?limit=N — most-recent-first run records.
+router.get('/history', asyncHandler(async (req, res) => {
+ const { limit } = validateRequest(personalityHistoryQuerySchema, req.query);
+ res.json(await modelPersonality.getHistory(limit));
+}));
+
+// DELETE /api/model-personality/history/:runId
+router.delete('/history/:runId', asyncHandler(async (req, res) => {
+ const removed = await modelPersonality.deleteResult(req.params.runId);
+ if (!removed) throw new ServerError('Result not found', { status: 404, code: 'NOT_FOUND' });
+ res.status(204).end();
+}));
+
+// GET /api/model-personality/settings
+router.get('/settings', asyncHandler(async (req, res) => {
+ res.json(await modelPersonality.getSettings());
+}));
+
+// PUT /api/model-personality/settings — partial update (scorer provider/model,
+// history cap, default alignment toggle).
+router.put('/settings', asyncHandler(async (req, res) => {
+ const patch = validateRequest(personalitySettingsUpdateSchema, req.body ?? {});
+ res.json(await modelPersonality.updateSettings(patch));
+}));
+
+export default router;
diff --git a/server/routes/model-personality.test.js b/server/routes/model-personality.test.js
new file mode 100644
index 0000000000..f4ae61d734
--- /dev/null
+++ b/server/routes/model-personality.test.js
@@ -0,0 +1,134 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+// Pin the ROUTE contract (Zod validation → 400, status mapping, exact service
+// call args); the service internals are covered in services/modelPersonality.test.js.
+const fnMap = vi.hoisted(() => (names) => Object.fromEntries(names.map((n) => [n, vi.fn()])));
+
+vi.mock('../services/modelPersonality.js', () => fnMap([
+ 'runPersonalityTest', 'getHistory', 'deleteResult', 'getSettings', 'updateSettings'
+]));
+
+import modelPersonalityRoutes from './model-personality.js';
+import * as modelPersonality from '../services/modelPersonality.js';
+
+describe('Model Personality Routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/model-personality', modelPersonalityRoutes);
+ vi.clearAllMocks();
+ });
+
+ describe('POST /run', () => {
+ it('runs the test and passes the exact validated args to the service', async () => {
+ const record = { runId: 'r1', model: 'effective', traits: {} };
+ modelPersonality.runPersonalityTest.mockResolvedValue(record);
+
+ const res = await request(app)
+ .post('/api/model-personality/run')
+ .send({ providerId: 'p1', model: 'm1', includeAlignment: true });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(record);
+ expect(modelPersonality.runPersonalityTest).toHaveBeenCalledExactlyOnceWith({
+ providerId: 'p1', model: 'm1', includeAlignment: true, personaId: undefined
+ });
+ });
+
+ it('400s without providerId and never calls the service', async () => {
+ const res = await request(app).post('/api/model-personality/run').send({ model: 'm1' });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(modelPersonality.runPersonalityTest).not.toHaveBeenCalled();
+ });
+
+ it('400s on a non-boolean includeAlignment', async () => {
+ const res = await request(app)
+ .post('/api/model-personality/run')
+ .send({ providerId: 'p1', includeAlignment: 'yes' });
+ expect(res.status).toBe(400);
+ expect(modelPersonality.runPersonalityTest).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('GET /history', () => {
+ it('returns history with a coerced limit', async () => {
+ modelPersonality.getHistory.mockResolvedValue([{ runId: 'r1' }]);
+ const res = await request(app).get('/api/model-personality/history?limit=5');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ runId: 'r1' }]);
+ expect(modelPersonality.getHistory).toHaveBeenCalledExactlyOnceWith(5);
+ });
+
+ it('passes undefined when no limit is supplied', async () => {
+ modelPersonality.getHistory.mockResolvedValue([]);
+ const res = await request(app).get('/api/model-personality/history');
+ expect(res.status).toBe(200);
+ expect(modelPersonality.getHistory).toHaveBeenCalledExactlyOnceWith(undefined);
+ });
+
+ it('400s on an invalid limit', async () => {
+ const res = await request(app).get('/api/model-personality/history?limit=0');
+ expect(res.status).toBe(400);
+ expect(modelPersonality.getHistory).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('DELETE /history/:runId', () => {
+ it('204s on success', async () => {
+ modelPersonality.deleteResult.mockResolvedValue(true);
+ const res = await request(app).delete('/api/model-personality/history/run-1');
+ expect(res.status).toBe(204);
+ expect(modelPersonality.deleteResult).toHaveBeenCalledExactlyOnceWith('run-1');
+ });
+
+ it('404s when nothing was deleted', async () => {
+ modelPersonality.deleteResult.mockResolvedValue(false);
+ const res = await request(app).delete('/api/model-personality/history/ghost');
+ expect(res.status).toBe(404);
+ expect(res.body.code).toBe('NOT_FOUND');
+ });
+ });
+
+ describe('settings', () => {
+ it('GET /settings returns the stored settings', async () => {
+ const settings = { scorerProviderId: null, scorerModel: null, historyCap: 200, defaultIncludeAlignment: true };
+ modelPersonality.getSettings.mockResolvedValue(settings);
+ const res = await request(app).get('/api/model-personality/settings');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(settings);
+ });
+
+ it('PUT /settings passes the validated partial patch through', async () => {
+ modelPersonality.updateSettings.mockResolvedValue({ historyCap: 50 });
+ const res = await request(app)
+ .put('/api/model-personality/settings')
+ .send({ historyCap: 50 });
+ expect(res.status).toBe(200);
+ expect(modelPersonality.updateSettings).toHaveBeenCalledExactlyOnceWith({ historyCap: 50 });
+ });
+
+ it('PUT /settings normalizes empty-string scorer sentinels to null', async () => {
+ modelPersonality.updateSettings.mockResolvedValue({});
+ const res = await request(app)
+ .put('/api/model-personality/settings')
+ .send({ scorerProviderId: '', scorerModel: '' });
+ expect(res.status).toBe(200);
+ expect(modelPersonality.updateSettings).toHaveBeenCalledExactlyOnceWith({
+ scorerProviderId: null, scorerModel: null
+ });
+ });
+
+ it('PUT /settings 400s on an out-of-bounds historyCap', async () => {
+ const res = await request(app)
+ .put('/api/model-personality/settings')
+ .send({ historyCap: 100000 });
+ expect(res.status).toBe(400);
+ expect(modelPersonality.updateSettings).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/server/services/modelPersonality.js b/server/services/modelPersonality.js
new file mode 100644
index 0000000000..451153194f
--- /dev/null
+++ b/server/services/modelPersonality.js
@@ -0,0 +1,218 @@
+/**
+ * Model Personality self-profile testing (issue #2610).
+ *
+ * Asks a chosen model to run a deep introspective self-evaluation in a single
+ * prompt and return a structured personality attribute map, plus an optional
+ * follow-up alignment score against the digital twin's stored trait profile.
+ *
+ * AI policy: both LLM calls fire ONLY from `runPersonalityTest`, which is only
+ * reachable via the explicit POST /api/model-personality/run user action —
+ * no boot-time calls, no background batches.
+ *
+ * Storage: results live in `data/model-personality/results.json` — a
+ * regenerable, capped, install-local log OUTSIDE `data/digital-twin/` (the
+ * twin dir is checksummed for federation and its meta.json merges whole-body
+ * LWW, which would lose appended history across machines). No dataSync
+ * category, no peer-sync record kind — provider ids are per-install anyway.
+ */
+
+import { randomUUID } from 'crypto';
+import { join } from 'path';
+import { PATHS, atomicWrite, readJSONFile } from '../lib/fileUtils.js';
+import { resolveProviderAndModel, runPromptThroughProvider, assertProvider } from '../lib/promptRunner.js';
+import {
+ PERSONALITY_TAXONOMY_VERSION,
+ PERSONALITY_TRAIT_KEYS,
+ personalityProfileResponseSchema,
+ personalityAlignmentResponseSchema
+} from '../lib/modelPersonalityValidation.js';
+import { buildPrompt } from './promptService.js';
+import { loadMeta } from './digital-twin-meta.js';
+
+export const DEFAULT_SETTINGS = Object.freeze({
+ scorerProviderId: null, // null → score with the same provider that self-profiled
+ scorerModel: null,
+ historyCap: 200,
+ defaultIncludeAlignment: true
+});
+
+export const ALIGNMENT_SKIPPED_NO_TRAITS =
+ 'The digital twin has no analyzed traits yet — run a trait analysis on the Digital Twin Identity tab first.';
+
+// Paths resolve lazily so test mocks that redirect PATHS.data take effect.
+const resultsFile = () => join(PATHS.data, 'model-personality', 'results.json');
+const settingsFile = () => join(PATHS.data, 'model-personality', 'settings.json');
+
+export async function getSettings() {
+ const stored = await readJSONFile(settingsFile(), {});
+ return { ...DEFAULT_SETTINGS, ...(stored && typeof stored === 'object' ? stored : {}) };
+}
+
+export async function updateSettings(patch = {}) {
+ const next = { ...(await getSettings()), ...patch };
+ await atomicWrite(settingsFile(), JSON.stringify(next, null, 2));
+ return next;
+}
+
+export async function getHistory(limit) {
+ const stored = await readJSONFile(resultsFile(), []);
+ const list = Array.isArray(stored) ? stored : [];
+ return typeof limit === 'number' ? list.slice(0, limit) : list;
+}
+
+// Serialize results.json mutations: a run finishing while a delete is in
+// flight would otherwise read-modify-write the same file and drop one of the
+// two changes. Single tail — every write awaits the previous one to settle.
+let writeTail = Promise.resolve();
+function withResultsWrite(fn) {
+ const run = writeTail.then(fn, fn);
+ writeTail = run.then(() => {}, () => {});
+ return run;
+}
+
+export async function deleteResult(runId) {
+ return withResultsWrite(async () => {
+ const list = await getHistory();
+ const next = list.filter((r) => r.runId !== runId);
+ if (next.length === list.length) return false;
+ await atomicWrite(resultsFile(), JSON.stringify(next, null, 2));
+ return true;
+ });
+}
+
+function appendResult(record, historyCap) {
+ return withResultsWrite(async () => {
+ const list = await getHistory();
+ list.unshift(record);
+ await atomicWrite(resultsFile(), JSON.stringify(list.slice(0, historyCap), null, 2));
+ });
+}
+
+/**
+ * Parse a runner response that was validated/coerced against `schema` by
+ * runPromptThroughProvider. The runner guarantees `text` satisfies the schema
+ * on success, so a failure here means the runner contract broke — surface it.
+ */
+function parseSchemaText(text, schema, label) {
+ const parsed = schema.safeParse(JSON.parse(text));
+ if (!parsed.success) throw new Error(`${label} response failed schema validation after runner coercion`);
+ return parsed.data;
+}
+
+/** True when the twin has at least one analyzed trait surface to align against. */
+export function twinHasTraits(traits) {
+ return !!(
+ traits &&
+ (traits.bigFive ||
+ traits.communicationProfile ||
+ (Array.isArray(traits.valuesHierarchy) && traits.valuesHierarchy.length > 0))
+ );
+}
+
+/**
+ * Run the personality self-profile test against one provider/model.
+ *
+ * Call 1 (always): the blind single-prompt self-evaluation — deliberately NO
+ * twin context, so the self-report isn't anchored on the target profile.
+ * Call 2 (only when alignment is requested AND the twin has analyzed traits):
+ * feed the self-reported map + twin traits to the configured scorer provider.
+ *
+ * Persists the EFFECTIVE provider/model the runner reports (CLI providers may
+ * ignore per-call overrides), unshifts the record into the capped history, and
+ * returns it.
+ */
+export async function runPersonalityTest({ providerId, model, includeAlignment, personaId = null } = {}) {
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, {
+ message: 'No AI provider available for the personality self-profile',
+ code: 'NO_PROVIDER'
+ });
+
+ const settings = await getSettings();
+ const wantAlignment = includeAlignment ?? settings.defaultIncludeAlignment;
+
+ const prompt = await buildPrompt('model-personality-profile', {
+ traitKeys: PERSONALITY_TRAIT_KEYS.join(', ')
+ });
+ const run = await runPromptThroughProvider({
+ provider,
+ prompt,
+ source: 'model-personality-profile',
+ model: selectedModel ?? undefined,
+ responseSchema: personalityProfileResponseSchema
+ });
+ const profile = parseSchemaText(run.text, personalityProfileResponseSchema, 'Self-profile');
+
+ const record = {
+ runId: randomUUID(),
+ providerId: run.provider?.id || provider.id,
+ model: run.model ?? selectedModel ?? null, // effective model, not the requested one
+ timestamp: new Date().toISOString(),
+ taxonomyVersion: PERSONALITY_TAXONOMY_VERSION,
+ traits: profile.traits,
+ summary: profile.summary,
+ ...(personaId ? { personaId } : {})
+ };
+
+ if (wantAlignment) {
+ Object.assign(record, await scoreAlignment(record, settings));
+ }
+
+ await appendResult(record, settings.historyCap);
+ console.log(
+ `🧠 Personality self-profile complete: ${record.providerId}/${record.model ?? 'default'}${
+ record.alignment ? ` — alignment ${Math.round(record.alignment.alignmentScore * 100)}%` : ''
+ }`
+ );
+ return record;
+}
+
+/**
+ * Score the self-reported profile against the twin's stored traits.
+ * Returns `{ alignment, scorerProviderId, scorerModel }` on success, or
+ * `{ alignmentSkipped }` with a clear message when the twin has no analyzed
+ * traits yet (no scorer call is made in that case).
+ */
+async function scoreAlignment(record, settings) {
+ const meta = await loadMeta();
+ if (!twinHasTraits(meta?.traits)) {
+ return { alignmentSkipped: ALIGNMENT_SKIPPED_NO_TRAITS };
+ }
+ const twinTraits = meta.traits;
+
+ const { provider, selectedModel } = await resolveProviderAndModel({
+ providerId: settings.scorerProviderId || record.providerId,
+ model: settings.scorerModel || undefined
+ });
+ assertProvider(provider, {
+ message: 'No AI provider available for the alignment scorer',
+ code: 'NO_PROVIDER'
+ });
+
+ const prompt = await buildPrompt('model-personality-alignment-scorer', {
+ selfProfile: JSON.stringify({ traits: record.traits, summary: record.summary }, null, 2),
+ twinTraits: JSON.stringify(
+ {
+ bigFive: twinTraits.bigFive,
+ communicationProfile: twinTraits.communicationProfile,
+ valuesHierarchy: twinTraits.valuesHierarchy
+ },
+ null,
+ 2
+ )
+ });
+ const run = await runPromptThroughProvider({
+ provider,
+ prompt,
+ source: 'model-personality-alignment',
+ model: selectedModel ?? undefined,
+ responseSchema: personalityAlignmentResponseSchema
+ });
+ const parsed = parseSchemaText(run.text, personalityAlignmentResponseSchema, 'Alignment');
+
+ return {
+ alignment: { alignmentScore: parsed.alignmentScore, dimensions: parsed.dimensions },
+ scorerProviderId: run.provider?.id || provider.id,
+ scorerModel: run.model ?? selectedModel ?? null
+ };
+}
diff --git a/server/services/modelPersonality.test.js b/server/services/modelPersonality.test.js
new file mode 100644
index 0000000000..d01838205b
--- /dev/null
+++ b/server/services/modelPersonality.test.js
@@ -0,0 +1,235 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, readFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import {
+ PERSONALITY_TRAIT_KEYS,
+ PERSONALITY_TAXONOMY_VERSION
+} from '../lib/modelPersonalityValidation.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'model-personality-test-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+
+// Full stub — promptRunner drags in the runner/provider stack transitively.
+vi.mock('../lib/promptRunner.js', () => ({
+ resolveProviderAndModel: vi.fn(),
+ runPromptThroughProvider: vi.fn(),
+ assertProvider: (provider, { message } = {}) => {
+ if (!provider) throw new Error(message || 'no provider');
+ }
+}));
+vi.mock('./promptService.js', () => ({
+ buildPrompt: vi.fn(async (stage) => `PROMPT:${stage}`)
+}));
+vi.mock('./digital-twin-meta.js', () => ({
+ loadMeta: vi.fn(async () => ({}))
+}));
+
+const { resolveProviderAndModel, runPromptThroughProvider } = await import('../lib/promptRunner.js');
+const { buildPrompt } = await import('./promptService.js');
+const { loadMeta } = await import('./digital-twin-meta.js');
+const svc = await import('./modelPersonality.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+const fullTraits = Object.fromEntries(
+ PERSONALITY_TRAIT_KEYS.map((k) => [k, { score: 0.4, rationale: `r-${k}` }])
+);
+const profileText = JSON.stringify({ traits: fullTraits, summary: 'measured and dry' });
+const alignmentText = JSON.stringify({
+ alignmentScore: 0.66,
+ dimensions: { agreeableness: { score: 0.7, note: 'close' } }
+});
+
+const provider = { id: 'prov-1', type: 'api', name: 'Prov One' };
+const scorerProvider = { id: 'prov-scorer', type: 'api', name: 'Scorer' };
+
+function mockProfileRun({ effectiveModel = 'effective-model', effectiveProviderId = 'prov-1' } = {}) {
+ runPromptThroughProvider.mockResolvedValueOnce({
+ text: profileText,
+ runId: 'run-a',
+ model: effectiveModel,
+ provider: { id: effectiveProviderId }
+ });
+}
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ resolveProviderAndModel.mockResolvedValue({ provider, selectedModel: 'requested-model' });
+ loadMeta.mockResolvedValue({});
+ // Reset persisted state between tests (fresh files under the temp root).
+ rmSync(join(TEST_DATA_ROOT, 'model-personality'), { recursive: true, force: true });
+});
+
+describe('runPersonalityTest', () => {
+ it('persists the EFFECTIVE model/provider the runner reports, not the requested one', async () => {
+ mockProfileRun({ effectiveModel: 'actually-ran-model', effectiveProviderId: 'prov-swapped' });
+
+ const record = await svc.runPersonalityTest({
+ providerId: 'prov-1', model: 'requested-model', includeAlignment: false
+ });
+
+ expect(record.model).toBe('actually-ran-model');
+ expect(record.providerId).toBe('prov-swapped');
+ expect(record.taxonomyVersion).toBe(PERSONALITY_TAXONOMY_VERSION);
+ expect(Object.keys(record.traits)).toEqual(expect.arrayContaining(PERSONALITY_TRAIT_KEYS));
+
+ // Survives a re-read from disk (restart-equivalent).
+ const onDisk = JSON.parse(
+ readFileSync(join(TEST_DATA_ROOT, 'model-personality', 'results.json'), 'utf8')
+ );
+ expect(onDisk).toHaveLength(1);
+ expect(onDisk[0].model).toBe('actually-ran-model');
+ });
+
+ it('passes a schema-bearing single self-eval call to the runner', async () => {
+ mockProfileRun();
+ await svc.runPersonalityTest({ providerId: 'prov-1', includeAlignment: false });
+
+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(1);
+ const args = runPromptThroughProvider.mock.calls[0][0];
+ expect(args.provider).toBe(provider);
+ expect(args.source).toBe('model-personality-profile');
+ expect(args.model).toBe('requested-model');
+ expect(args.responseSchema).toBeTruthy();
+ expect(buildPrompt).toHaveBeenCalledWith('model-personality-profile', {
+ traitKeys: PERSONALITY_TRAIT_KEYS.join(', ')
+ });
+ });
+
+ it('skips the alignment call with a clear message when the twin has no analyzed traits', async () => {
+ mockProfileRun();
+ loadMeta.mockResolvedValue({ traits: undefined });
+
+ const record = await svc.runPersonalityTest({ providerId: 'prov-1', includeAlignment: true });
+
+ expect(record.alignmentSkipped).toBe(svc.ALIGNMENT_SKIPPED_NO_TRAITS);
+ expect(record.alignment).toBeUndefined();
+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(1); // profile only — no scorer call
+ });
+
+ it('scores alignment against stored twin traits with the configured scorer provider', async () => {
+ await svc.updateSettings({ scorerProviderId: 'prov-scorer', scorerModel: 'scorer-model' });
+ loadMeta.mockResolvedValue({ traits: { bigFive: { openness: 0.8 }, valuesHierarchy: [] } });
+ mockProfileRun();
+ resolveProviderAndModel
+ .mockResolvedValueOnce({ provider, selectedModel: 'requested-model' }) // profile
+ .mockResolvedValueOnce({ provider: scorerProvider, selectedModel: 'scorer-model' }); // scorer
+ runPromptThroughProvider.mockResolvedValueOnce({
+ text: alignmentText, runId: 'run-b', model: 'scorer-effective', provider: { id: 'prov-scorer' }
+ });
+
+ const record = await svc.runPersonalityTest({ providerId: 'prov-1', includeAlignment: true });
+
+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(2);
+ expect(record.alignment).toEqual({
+ alignmentScore: 0.66,
+ dimensions: { agreeableness: { score: 0.7, note: 'close' } }
+ });
+ expect(record.scorerProviderId).toBe('prov-scorer');
+ expect(record.scorerModel).toBe('scorer-effective');
+ // The scorer resolution honored the saved settings.
+ expect(resolveProviderAndModel).toHaveBeenLastCalledWith({
+ providerId: 'prov-scorer', model: 'scorer-model'
+ });
+ });
+
+ it('defaults includeAlignment from settings when the caller omits it', async () => {
+ await svc.updateSettings({ defaultIncludeAlignment: false });
+ mockProfileRun();
+
+ const record = await svc.runPersonalityTest({ providerId: 'prov-1' });
+
+ expect(record.alignment).toBeUndefined();
+ expect(record.alignmentSkipped).toBeUndefined();
+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(1);
+ });
+
+ it('caps history at the configured historyCap, newest first', async () => {
+ await svc.updateSettings({ historyCap: 3 });
+ for (let i = 0; i < 5; i++) {
+ mockProfileRun({ effectiveModel: `model-${i}` });
+ await svc.runPersonalityTest({ providerId: 'prov-1', includeAlignment: false });
+ }
+ const history = await svc.getHistory();
+ expect(history).toHaveLength(3);
+ expect(history.map((r) => r.model)).toEqual(['model-4', 'model-3', 'model-2']);
+ });
+
+ it('tags the record with personaId when supplied', async () => {
+ mockProfileRun();
+ const record = await svc.runPersonalityTest({
+ providerId: 'prov-1', includeAlignment: false, personaId: 'persona-9'
+ });
+ expect(record.personaId).toBe('persona-9');
+ });
+});
+
+describe('history & settings', () => {
+ it('getHistory honors limit and tolerates a missing file', async () => {
+ expect(await svc.getHistory()).toEqual([]);
+ mockProfileRun();
+ await svc.runPersonalityTest({ providerId: 'prov-1', includeAlignment: false });
+ mockProfileRun();
+ await svc.runPersonalityTest({ providerId: 'prov-1', includeAlignment: false });
+ expect(await svc.getHistory(1)).toHaveLength(1);
+ expect(await svc.getHistory()).toHaveLength(2);
+ });
+
+ it('deleteResult removes a run and reports false for an unknown id', async () => {
+ mockProfileRun();
+ const record = await svc.runPersonalityTest({ providerId: 'prov-1', includeAlignment: false });
+ expect(await svc.deleteResult('nope')).toBe(false);
+ expect(await svc.deleteResult(record.runId)).toBe(true);
+ expect(await svc.getHistory()).toEqual([]);
+ });
+
+ it('merges settings over defaults and persists them', async () => {
+ expect(await svc.getSettings()).toEqual({ ...svc.DEFAULT_SETTINGS });
+ const next = await svc.updateSettings({ historyCap: 42 });
+ expect(next.historyCap).toBe(42);
+ expect(next.defaultIncludeAlignment).toBe(true); // untouched default survives
+ expect((await svc.getSettings()).historyCap).toBe(42);
+ });
+});
+
+describe('twinHasTraits', () => {
+ it('detects each trait surface and rejects empty shapes', () => {
+ expect(svc.twinHasTraits(null)).toBe(false);
+ expect(svc.twinHasTraits({})).toBe(false);
+ expect(svc.twinHasTraits({ valuesHierarchy: [] })).toBe(false);
+ expect(svc.twinHasTraits({ bigFive: { openness: 0.5 } })).toBe(true);
+ expect(svc.twinHasTraits({ communicationProfile: { formality: 0.5 } })).toBe(true);
+ expect(svc.twinHasTraits({ valuesHierarchy: [{ value: 'honesty', priority: 1 }] })).toBe(true);
+ });
+});
+
+describe('shipped prompt templates', () => {
+ const stagesDir = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'data.reference', 'prompts', 'stages');
+ const tokensOf = (name) =>
+ [...readFileSync(join(stagesDir, name), 'utf8').matchAll(/\{\{\s*([\w.]+)\s*\}\}/g)].map((m) => m[1]);
+
+ it('model-personality-profile.md interpolates exactly the variables the service passes', () => {
+ expect([...new Set(tokensOf('model-personality-profile.md'))]).toEqual(['traitKeys']);
+ });
+
+ it('model-personality-alignment-scorer.md interpolates exactly the variables the service passes', () => {
+ expect([...new Set(tokensOf('model-personality-alignment-scorer.md'))].sort()).toEqual([
+ 'selfProfile', 'twinTraits'
+ ]);
+ });
+
+ it('stage-config.json ships both stages flagged returnsJson', () => {
+ const config = JSON.parse(
+ readFileSync(join(stagesDir, '..', 'stage-config.json'), 'utf8')
+ );
+ for (const key of ['model-personality-profile', 'model-personality-alignment-scorer']) {
+ expect(config.stages[key], key).toBeTruthy();
+ expect(config.stages[key].returnsJson, key).toBe(true);
+ }
+ });
+});