Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add Likert-scale trait scoring to digital twin enrichment
Adam Eivy3dfdc893780a
diff --git a/.changelog/v0.11.x.md b/.changelog/v0.11.x.mdindex f9312f9934..f3d5c605d5 100644--- a/.changelog/v0.11.x.md+++ b/.changelog/v0.11.x.md@@ -29,14 +29,32 @@ This release focuses on security improvements, bug fixes for the AI runner syste- `portos-ai-toolkit/src/server/providers.js` - Universal refresh implementation- `client/src/pages/AIProviders.jsx` - UI updates with toast notifications-### Digital Twin AI Interview Chat-- New "Interview" tab in Digital Twin for building personality profiles via external AI conversation loops-- Paste personality data from ChatGPT/other AIs for automated analysis and twin record updates-- AI-powered follow-up question generation to deepen profile coverage-- Persistent chat sessions with session management (create, rename, delete)+### Digital Twin Interview & Enrichment Guide+- Redesigned "Interview" tab as a single-page assessment analyzer + enrichment guide+- Paste AI personality assessments for automated analysis and twin profile updates+- Enrichment gap dashboard shows which areas need the most attention+- Direct navigation from gaps to specific enrichment categories- Automatically maps traits to Big Five, values, and communication dimensions-- Creates new documents for trait categories not yet captured (Cognitive, Creative, Technical, etc.)-- Linkable sessions via URL query params (`/digital-twin/interview?session=<uuid>`)+- Creates new documents for personality dimensions not yet captured+- Removed session-based chat interface in favor of simpler paste-and-analyze flow++### Digital Twin Enrichment UX Improvements+- **Deep-link Enrich buttons**: All "Enrich" buttons on gap cards and completeness missing sections now navigate directly to the specific enrichment category (e.g., `/digital-twin/enrich?category=values`) instead of the generic landing page+- **"Start Enrichment Session" targets top gap**: The main CTA button uses the most critical gap's category for immediate action+- **"Enrich Soul" quick action uses top gap**: The overview quick action card navigates to the highest-priority gap's category when available+- **Next Action Banner on Overview**: New contextual banner at the top of the overview tab with three modes:+ - **No profile yet**: Suggests pasting a personality assessment via the Interview tab+ - **Gaps exist (Q&A)**: Shows an inline question from the top gap's category with submit/skip, Ctrl+Enter shortcut, and link to full enrichment+ - **Gaps exist (list-based)**: Shows a navigate prompt for list categories (books, movies, music)+ - **All caught up**: Confirms the twin is well-defined and links to behavioral tests++### Likert-Scale Trait Scoring for Digital Twin Enrichment+- **Immediate Trait Feedback**: Enrichment now includes 1-5 Likert-scale questions that directly update trait scores and confidence when answered, closing the loop between enrichment answers and personality modeling+- **18 Scale Questions**: Covers Big Five (10 items), communication style (2), daily routines (2), values (2), and decision heuristics (2) — each mapped to a specific trait dimension+- **Weighted Moving Average**: Scale answers blend with existing scores using a 0.3 weight factor, preventing any single answer from dominating while still moving the needle+- **Confidence Boost**: Each scale answer adds +0.15 to the relevant dimension's confidence score, so 3-4 answers can cross the 0.6 gap threshold and remove that dimension from recommendations+- **Inline Scale UI**: New `ScaleInput` component renders 5 touch-friendly buttons with labels, working in both the full EnrichTab and the NextActionBanner's quick-enrich mode+- **Backward Compatible**: `questionType` defaults to `text`, existing text question flow is completely unchanged, old client submissions still work## 🐛 Bug Fixes@@ -75,6 +93,10 @@ This release focuses on security improvements, bug fixes for the AI runner syste- **Immediate Task Blocking**: Both `terminateAgent()` and `killAgent()` in direct mode now immediately update the task to `blocked` with `user-terminated` category, matching the runner mode behavior. Previously, task blocking was deferred to the close handler, creating a window where server restarts could cause requeue- **Orphan Handler Guard**: `handleOrphanedTask()` now skips tasks already marked as `user-terminated`, preventing any residual requeue path+### Digital Twin Personality Trait Confidence Display & Recalculation+- **Low confidence bars now grey instead of red**: Personality trait bars with low confidence (<60%) now display as grey rather than red, avoiding the false impression of errors when data is simply unverified or sparse+- **Confidence recalculates after trait analysis**: Running "Analyze Traits" or processing an AI interview assessment now automatically recalculates confidence scores, so the displayed confidence reflects the latest data instead of remaining stale from a previous manual calculation+### Autofixer App Replaced with PortOS Default- Replaced the standalone Autofixer app with PortOS default app in sample data to avoid confusiondiff --git a/client/src/components/digital-twin/NextActionBanner.jsx b/client/src/components/digital-twin/NextActionBanner.jsxnew file mode 100644index 0000000000..5dd2f7f6f2--- /dev/null+++ b/client/src/components/digital-twin/NextActionBanner.jsx@@ -0,0 +1,266 @@+import { useState, useEffect } from 'react';+import { useNavigate } from 'react-router-dom';+import {+ Sparkles,+ Send,+ SkipForward,+ RefreshCw,+ ArrowRight,+ CheckCircle,+ MessageSquare+} from 'lucide-react';+import * as api from '../../services/api';+import toast from 'react-hot-toast';+import { ENRICHMENT_CATEGORIES } from './constants';+import ScaleInput from './ScaleInput';++const DIMENSION_LABELS = {+ openness: 'Openness',+ conscientiousness: 'Conscientiousness',+ extraversion: 'Extraversion',+ agreeableness: 'Agreeableness',+ neuroticism: 'Neuroticism',+ values: 'Values',+ communication: 'Communication',+ decision_making: 'Decision Making',+ boundaries: 'Boundaries',+ identity: 'Identity'+};++function getUrgencyBadge(confidence) {+ if (confidence < 0.3) return { text: 'Critical', cls: 'text-red-400 bg-red-500/20' };+ if (confidence < 0.5) return { text: 'Important', cls: 'text-orange-400 bg-orange-500/20' };+ return { text: 'Suggested', cls: 'text-yellow-400 bg-yellow-500/20' };+}++export default function NextActionBanner({ gaps, status, traits, onRefresh }) {+ const navigate = useNavigate();+ const [question, setQuestion] = useState(null);+ const [answer, setAnswer] = useState('');+ const [scaleValue, setScaleValue] = useState(null);+ const [loading, setLoading] = useState(false);+ const [submitting, setSubmitting] = useState(false);++ const hasTraits = traits && Object.keys(traits).length > 0;+ const hasEnrichment = (status?.enrichmentProgress?.completedCategories || 0) > 0;+ const hasGaps = gaps && gaps.length > 0;++ const topGap = hasGaps ? gaps[0] : null;+ const topCategory = topGap?.suggestedCategory;+ const isListBased = topCategory && ENRICHMENT_CATEGORIES[topCategory]?.listBased;++ // Load a question for the top gap's category (only for Q&A categories)+ useEffect(() => {+ if (topCategory && !isListBased) {+ loadQuestion(topCategory);+ }+ }, [topCategory, isListBased]);++ const loadQuestion = async (category) => {+ setLoading(true);+ const q = await api.getSoulEnrichQuestion(category).catch(() => null);+ setQuestion(q);+ setAnswer('');+ setScaleValue(null);+ setLoading(false);+ };++ const handleSubmit = async () => {+ if (!question) return;+ const isScale = question.questionType === 'scale';++ if (isScale && scaleValue == null) return;+ if (!isScale && !answer.trim()) return;++ setSubmitting(true);++ const payload = {+ questionId: question.questionId,+ category: topCategory,+ question: question.question+ };++ if (isScale) {+ payload.questionType = 'scale';+ payload.scaleValue = scaleValue;+ payload.scaleQuestionId = question.scaleQuestionId;+ } else {+ payload.questionType = 'text';+ payload.answer = answer.trim();+ }++ await api.submitSoulEnrichAnswer(payload);+ toast.success(isScale ? 'Rating saved' : 'Answer saved');+ setAnswer('');+ setScaleValue(null);+ onRefresh?.();+ await loadQuestion(topCategory);+ setSubmitting(false);+ };++ const handleSkip = () => {+ if (topCategory) loadQuestion(topCategory);+ };++ const handleKeyDown = (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {+ const isScale = question?.questionType === 'scale';+ if (isScale ? scaleValue != null : answer.trim()) handleSubmit();+ }+ };++ // Mode 1: No traits and no enrichment - suggest interview+ if (!hasTraits && !hasEnrichment) {+ return (+ <div className="bg-gradient-to-r from-purple-500/10 to-pink-500/10 border border-purple-500/30 rounded-lg p-5">+ <div className="flex items-start gap-3">+ <MessageSquare className="w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0" />+ <div className="flex-1">+ <h3 className="text-white font-medium mb-1">Get started with a personality assessment</h3>+ <p className="text-sm text-gray-400 mb-3">+ Paste results from a personality test (Big Five, MBTI, Enneagram) to quickly seed your digital twin profile.+ </p>+ <button+ onClick={() => navigate('/digital-twin/interview')}+ className="px-4 py-2 bg-purple-600 text-white rounded-lg text-sm hover:bg-purple-500 flex items-center gap-2"+ >+ Go to Interview+ <ArrowRight size={14} />+ </button>+ </div>+ </div>+ </div>+ );+ }++ // Mode 3: No gaps - all caught up+ if (!hasGaps) {+ return (+ <div className="bg-green-500/10 border border-green-500/30 rounded-lg p-5">+ <div className="flex items-start gap-3">+ <CheckCircle className="w-5 h-5 text-green-400 mt-0.5 flex-shrink-0" />+ <div className="flex-1">+ <h3 className="text-white font-medium mb-1">Your twin is well-defined</h3>+ <p className="text-sm text-gray-400 mb-3">+ All personality dimensions have strong confidence. Run behavioral tests to validate accuracy.+ </p>+ <button+ onClick={() => navigate('/digital-twin/test')}+ className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm hover:bg-green-500 flex items-center gap-2"+ >+ Run Tests+ <ArrowRight size={14} />+ </button>+ </div>+ </div>+ </div>+ );+ }++ // Mode 2: Gaps exist - inline question or navigate prompt+ const urgency = getUrgencyBadge(topGap.confidence);+ const dimensionLabel = DIMENSION_LABELS[topGap.dimension] || topGap.dimension;++ // List-based category: show navigate prompt instead of inline Q&A+ if (isListBased) {+ const catConfig = ENRICHMENT_CATEGORIES[topCategory];+ return (+ <div className="bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border border-yellow-500/30 rounded-lg p-5">+ <div className="flex items-start gap-3">+ <Sparkles className="w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0" />+ <div className="flex-1">+ <div className="flex items-center gap-2 mb-1">+ <h3 className="text-white font-medium">Enrich: {dimensionLabel}</h3>+ <span className={`text-xs px-2 py-0.5 rounded-full ${urgency.cls}`}>{urgency.text}</span>+ </div>+ <p className="text-sm text-gray-400 mb-3">+ Add your {catConfig?.label?.toLowerCase() || 'items'} to strengthen this dimension.+ </p>+ <button+ onClick={() => navigate(`/digital-twin/enrich?category=${topCategory}`)}+ className="px-4 py-2 bg-yellow-600 text-white rounded-lg text-sm hover:bg-yellow-500 flex items-center gap-2"+ >+ Add {catConfig?.label || 'Items'}+ <ArrowRight size={14} />+ </button>+ </div>+ </div>+ </div>+ );+ }++ // Q&A-based category: inline question+ return (+ <div className="bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border border-yellow-500/30 rounded-lg p-5">+ <div className="flex items-start gap-3">+ <Sparkles className="w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-1">+ <h3 className="text-white font-medium">Quick Enrich: {dimensionLabel}</h3>+ <span className={`text-xs px-2 py-0.5 rounded-full ${urgency.cls}`}>{urgency.text}</span>+ </div>++ {loading ? (+ <div className="flex items-center gap-2 text-gray-400 py-4">+ <RefreshCw className="w-4 h-4 animate-spin" />+ Loading question...+ </div>+ ) : question ? (+ <>+ <p className="text-sm text-gray-300 mb-3">{question.question}</p>+ {question.questionType === 'scale' ? (+ <div className="mb-2">+ <ScaleInput+ labels={question.labels}+ value={scaleValue}+ onChange={setScaleValue}+ disabled={submitting}+ />+ </div>+ ) : (+ <textarea+ value={answer}+ onChange={(e) => setAnswer(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder="Type your answer..."+ rows={3}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm resize-none focus:outline-none focus:border-port-accent mb-2"+ />+ )}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <button+ onClick={handleSubmit}+ disabled={submitting || (question.questionType === 'scale' ? scaleValue == null : !answer.trim())}+ className="px-3 py-1.5 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 disabled:opacity-50 flex items-center gap-1.5"+ >+ {submitting ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Send size={14} />}+ Submit+ </button>+ <button+ onClick={handleSkip}+ className="px-3 py-1.5 text-gray-400 hover:text-white text-sm flex items-center gap-1.5"+ >+ <SkipForward size={14} />+ Skip+ </button>+ </div>+ <button+ onClick={() => navigate(`/digital-twin/enrich?category=${topCategory}`)}+ className="text-xs text-port-accent hover:text-white"+ >+ Full enrichment →+ </button>+ </div>+ {question.questionType !== 'scale' && (+ <div className="text-xs text-gray-600 mt-1">Ctrl+Enter to submit</div>+ )}+ </>+ ) : (+ <p className="text-sm text-gray-400">Unable to load question.</p>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/digital-twin/ScaleInput.jsx b/client/src/components/digital-twin/ScaleInput.jsxnew file mode 100644index 0000000000..1eba7ca622--- /dev/null+++ b/client/src/components/digital-twin/ScaleInput.jsx@@ -0,0 +1,30 @@+export default function ScaleInput({ labels, value, onChange, disabled }) {+ const defaultLabels = ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'];+ const shortLabels = ['SD', 'D', 'N', 'A', 'SA'];+ const displayLabels = labels || defaultLabels;++ return (+ <div className="flex gap-2 justify-center">+ {[1, 2, 3, 4, 5].map((val) => {+ const selected = value === val;+ return (+ <button+ key={val}+ type="button"+ disabled={disabled}+ onClick={() => onChange(val)}+ className={`flex-1 min-w-[48px] min-h-[48px] flex flex-col items-center justify-center rounded-lg border transition-all ${+ selected+ ? 'bg-port-accent border-port-accent text-white'+ : 'bg-port-bg border-port-border text-gray-400 hover:border-gray-500 hover:text-gray-300'+ } ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}+ >+ <span className="text-lg font-bold">{val}</span>+ <span className="text-[10px] leading-tight mt-0.5 hidden sm:block">{displayLabels[val - 1]}</span>+ <span className="text-[10px] leading-tight mt-0.5 sm:hidden">{shortLabels[val - 1]}</span>+ </button>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.jsindex 9d5a2885f7..9b70cf7d88 100644--- a/client/src/components/digital-twin/constants.js+++ b/client/src/components/digital-twin/constants.js@@ -33,6 +33,7 @@ export const TABS = [{ id: 'test', label: 'Test', icon: CheckCircle },{ id: 'enrich', label: 'Enrich', icon: Sparkles },{ id: 'accounts', label: 'Accounts', icon: Globe },+ { id: 'interview', label: 'Interview', icon: MessageSquare },{ id: 'import', label: 'Import', icon: Upload },{ id: 'export', label: 'Export', icon: Download }];@@ -153,7 +154,8 @@ export const ENRICHMENT_CATEGORIES = {label: 'Communication Style',description: 'How you prefer to give and receive information',icon: MessageSquare,- color: 'cyan'+ color: 'cyan',+ hasScaleQuestions: true},decision_making: {id: 'decision_making',@@ -167,7 +169,8 @@ export const ENRICHMENT_CATEGORIES = {label: 'Values',description: 'Core principles that guide your actions',icon: Heart,- color: 'pink'+ color: 'pink',+ hasScaleQuestions: true},aesthetics: {id: 'aesthetics',@@ -181,7 +184,8 @@ export const ENRICHMENT_CATEGORIES = {label: 'Daily Routines',description: 'Habits and rhythms that structure your day',icon: Clock,- color: 'amber'+ color: 'amber',+ hasScaleQuestions: true},career_skills: {id: 'career_skills',@@ -202,7 +206,8 @@ export const ENRICHMENT_CATEGORIES = {label: 'Decision Heuristics',description: 'Mental models and shortcuts for making choices',icon: GitBranch,- color: 'indigo'+ color: 'indigo',+ hasScaleQuestions: true},error_intolerance: {id: 'error_intolerance',@@ -216,7 +221,8 @@ export const ENRICHMENT_CATEGORIES = {label: 'Personality Assessments',description: 'Myers-Briggs, Big Five, Enneagram, and other personality type results',icon: Fingerprint,- color: 'sky'+ color: 'sky',+ hasScaleQuestions: true}};diff --git a/client/src/components/digital-twin/tabs/EnrichTab.jsx b/client/src/components/digital-twin/tabs/EnrichTab.jsxindex 2cef481ae3..9ee42776d6 100644--- a/client/src/components/digital-twin/tabs/EnrichTab.jsx+++ b/client/src/components/digital-twin/tabs/EnrichTab.jsx@@ -1,4 +1,5 @@import { useState, useEffect } from 'react';+import { useSearchParams } from 'react-router-dom';import {Sparkles,ChevronRight,@@ -17,8 +18,10 @@ import toast from 'react-hot-toast';import { ENRICHMENT_CATEGORIES } from '../constants';import ListEnrichment from '../ListEnrichment';+import ScaleInput from '../ScaleInput';export default function EnrichTab({ onRefresh }) {+ const [searchParams, setSearchParams] = useSearchParams();const [categories, setCategories] = useState([]);const [progress, setProgress] = useState(null);const [loading, setLoading] = useState(true);@@ -27,6 +30,7 @@ export default function EnrichTab({ onRefresh }) {const [activeCategory, setActiveCategory] = useState(null);const [currentQuestion, setCurrentQuestion] = useState(null);const [answer, setAnswer] = useState('');+ const [scaleValue, setScaleValue] = useState(null);const [submitting, setSubmitting] = useState(false);const [loadingQuestion, setLoadingQuestion] = useState(false);@@ -44,6 +48,16 @@ export default function EnrichTab({ onRefresh }) {loadProviders();}, []);+ // Auto-select category from query param+ useEffect(() => {+ const categoryParam = searchParams.get('category');+ if (categoryParam && ENRICHMENT_CATEGORIES[categoryParam] && !loading) {+ startCategory(categoryParam);+ // Clear the param so back navigation works cleanly+ setSearchParams({}, { replace: true });+ }+ }, [loading, searchParams]);+const loadData = async () => {setLoading(true);const [categoriesData, progressData] = await Promise.all([@@ -148,24 +162,42 @@ export default function EnrichTab({ onRefresh }) {const question = await api.getSoulEnrichQuestion(categoryId);setCurrentQuestion(question);setAnswer('');+ setScaleValue(null);setLoadingQuestion(false);};const submitAnswer = async () => {- if (!answer.trim()) {+ const isScale = currentQuestion?.questionType === 'scale';++ if (isScale && scaleValue == null) {+ toast.error('Please select a rating');+ return;+ }+ if (!isScale && !answer.trim()) {toast.error('Please provide an answer');return;}setSubmitting(true);- await api.submitSoulEnrichAnswer({++ const payload = {questionId: currentQuestion.questionId,category: activeCategory,- question: currentQuestion.question,- answer: answer.trim()- });+ question: currentQuestion.question+ };- toast.success('Answer saved');+ if (isScale) {+ payload.questionType = 'scale';+ payload.scaleValue = scaleValue;+ payload.scaleQuestionId = currentQuestion.scaleQuestionId;+ } else {+ payload.questionType = 'text';+ payload.answer = answer.trim();+ }++ await api.submitSoulEnrichAnswer(payload);++ toast.success(isScale ? 'Rating saved' : 'Answer saved');await loadData();// Load next question@@ -182,6 +214,7 @@ export default function EnrichTab({ onRefresh }) {setActiveCategory(null);setCurrentQuestion(null);setAnswer('');+ setScaleValue(null);};if (loading) {@@ -265,23 +298,34 @@ export default function EnrichTab({ onRefresh }) {<div className="bg-port-card rounded-lg border border-port-border p-6"><div className="mb-6"><span className="text-xs text-gray-500 uppercase tracking-wider">- {currentQuestion.isGenerated ? 'AI Generated Follow-up' : 'Core Question'}+ {currentQuestion.questionType === 'scale' ? 'Rate This Statement' : currentQuestion.isGenerated ? 'AI Generated Follow-up' : 'Core Question'}</span><h3 className="text-xl text-white mt-2">{currentQuestion.question}</h3></div><div className="mb-6">- <textarea- value={answer}- onChange={(e) => setAnswer(e.target.value)}- placeholder="Type your answer here..."- rows={6}- className="w-full px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white resize-none focus:outline-none focus:border-port-accent"- autoFocus- />- <div className="text-xs text-gray-500 mt-2">- Be as specific as possible. Your answers help create a more accurate digital twin.- </div>+ {currentQuestion.questionType === 'scale' ? (+ <ScaleInput+ labels={currentQuestion.labels}+ value={scaleValue}+ onChange={setScaleValue}+ disabled={submitting}+ />+ ) : (+ <>+ <textarea+ value={answer}+ onChange={(e) => setAnswer(e.target.value)}+ placeholder="Type your answer here..."+ rows={6}+ className="w-full px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white resize-none focus:outline-none focus:border-port-accent"+ autoFocus+ />+ <div className="text-xs text-gray-500 mt-2">+ Be as specific as possible. Your answers help create a more accurate digital twin.+ </div>+ </>+ )}</div><div className="flex flex-col-reverse sm:flex-row items-stretch sm:items-center justify-between gap-3">@@ -295,7 +339,7 @@ export default function EnrichTab({ onRefresh }) {<buttononClick={submitAnswer}- disabled={submitting || !answer.trim()}+ disabled={submitting || (currentQuestion?.questionType === 'scale' ? scaleValue == null : !answer.trim())}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">{submitting ? (diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex 6be5cf968f..73b36d93f4 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -78,7 +78,8 @@ export const testResultSchema = z.object({export const enrichmentProgressSchema = z.object({completedCategories: z.array(enrichmentCategoryEnum).default([]),lastSession: z.string().datetime().nullable().optional(),- questionsAnswered: z.record(enrichmentCategoryEnum, z.number().int().min(0)).optional()+ questionsAnswered: z.record(enrichmentCategoryEnum, z.number().int().min(0)).optional(),+ scaleQuestionsAnswered: z.record(z.string(), z.number().int().min(1).max(5)).optional()});// Digital Twin settings schema@@ -213,10 +214,17 @@ export const enrichmentAnswerInputSchema = z.object({questionId: z.string().uuid(),category: enrichmentCategoryEnum,question: z.string().min(1),- answer: z.string().min(1).max(10000),+ answer: z.string().min(1).max(10000).optional(),+ scaleValue: z.number().int().min(1).max(5).optional(),+ questionType: z.enum(['text', 'scale']).default('text'),+ scaleQuestionId: z.string().optional(),providerOverride: z.string().optional(),modelOverride: z.string().optional()-});+}).refine(+ data => (data.questionType === 'text' && data.answer) ||+ (data.questionType === 'scale' && data.scaleValue != null),+ { message: 'Text questions require answer; scale questions require scaleValue' }+);// Export inputexport const exportInputSchema = z.object({@@ -357,6 +365,15 @@ export const importDataInputSchema = z.object({model: z.string().min(1)});+// --- Assessment Analyzer Schema ---++// Analyze assessment input+export const analyzeAssessmentInputSchema = z.object({+ content: z.string().min(50, 'Assessment must be at least 50 characters'),+ providerId: z.string().min(1),+ model: z.string().min(1)+});+// Import analysis resultexport const importAnalysisResultSchema = z.object({source: importSourceEnum,diff --git a/server/services/digital-twin.js b/server/services/digital-twin.jsindex a6c584f2e2..4d380c6bee 100644--- a/server/services/digital-twin.js+++ b/server/services/digital-twin.js@@ -223,6 +223,40 @@ export const ENRICHMENT_CATEGORIES = {}};+// Scale questions for Likert-based trait scoring (1-5)+export const SCALE_QUESTIONS = [+ // Big Five — Openness (2 items)+ { id: 'bf-o-1', text: 'I enjoy exploring new ideas and unconventional perspectives.', category: 'personality_assessments', dimension: 'openness', trait: 'O', traitPath: 'bigFive.O', direction: 1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ { id: 'bf-o-2', text: 'I prefer familiar routines over trying something new.', category: 'personality_assessments', dimension: 'openness', trait: 'O', traitPath: 'bigFive.O', direction: -1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ // Big Five — Conscientiousness (2 items)+ { id: 'bf-c-1', text: 'I keep a detailed plan and follow through on commitments.', category: 'personality_assessments', dimension: 'conscientiousness', trait: 'C', traitPath: 'bigFive.C', direction: 1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ { id: 'bf-c-2', text: 'I tend to leave things unfinished or improvise instead of planning.', category: 'personality_assessments', dimension: 'conscientiousness', trait: 'C', traitPath: 'bigFive.C', direction: -1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ // Big Five — Extraversion (2 items)+ { id: 'bf-e-1', text: 'I feel energized after spending time with a group of people.', category: 'personality_assessments', dimension: 'extraversion', trait: 'E', traitPath: 'bigFive.E', direction: 1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ { id: 'bf-e-2', text: 'I prefer solitary activities over social gatherings.', category: 'personality_assessments', dimension: 'extraversion', trait: 'E', traitPath: 'bigFive.E', direction: -1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ // Big Five — Agreeableness (2 items)+ { id: 'bf-a-1', text: 'I go out of my way to help others, even at personal cost.', category: 'personality_assessments', dimension: 'agreeableness', trait: 'A', traitPath: 'bigFive.A', direction: 1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ { id: 'bf-a-2', text: 'I prioritize my own goals over group harmony.', category: 'personality_assessments', dimension: 'agreeableness', trait: 'A', traitPath: 'bigFive.A', direction: -1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ // Big Five — Neuroticism (2 items)+ { id: 'bf-n-1', text: 'I frequently worry about things that might go wrong.', category: 'personality_assessments', dimension: 'neuroticism', trait: 'N', traitPath: 'bigFive.N', direction: 1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ { id: 'bf-n-2', text: 'I stay calm and composed under pressure.', category: 'personality_assessments', dimension: 'neuroticism', trait: 'N', traitPath: 'bigFive.N', direction: -1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ // Communication — formality + verbosity (2 items)+ { id: 'comm-f', text: 'I prefer formal, structured language over casual speech.', category: 'communication', dimension: 'communication', trait: 'formality', traitPath: 'communicationProfile.formality', direction: 1, labels: ['Very Casual', 'Casual', 'Balanced', 'Formal', 'Very Formal'] },+ { id: 'comm-v', text: 'I prefer thorough, detailed explanations over brief answers.', category: 'communication', dimension: 'communication', trait: 'verbosity', traitPath: 'communicationProfile.verbosity', direction: 1, labels: ['Very Terse', 'Brief', 'Balanced', 'Detailed', 'Very Elaborate'] },+ // Daily routines — conscientiousness proxy (2 items)+ { id: 'rout-1', text: 'My day follows a consistent structure and set of rituals.', category: 'daily_routines', dimension: 'conscientiousness', trait: 'C', traitPath: 'bigFive.C', direction: 1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ { id: 'rout-2', text: 'I adapt my schedule spontaneously based on how I feel.', category: 'daily_routines', dimension: 'conscientiousness', trait: 'C', traitPath: 'bigFive.C', direction: -1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ // Values (2 items)+ { id: 'val-1', text: 'I would sacrifice personal gain to uphold a principle.', category: 'values', dimension: 'values', trait: 'values', traitPath: null, direction: 1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ { id: 'val-2', text: 'Pragmatism matters more to me than idealism.', category: 'values', dimension: 'values', trait: 'values', traitPath: null, direction: -1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ // Decision heuristics (2 items)+ { id: 'dec-1', text: 'I make decisions quickly with available information rather than waiting.', category: 'decision_heuristics', dimension: 'decision_making', trait: 'decision_making', traitPath: null, direction: 1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] },+ { id: 'dec-2', text: 'I prefer to gather extensive data before committing to a choice.', category: 'decision_heuristics', dimension: 'decision_making', trait: 'decision_making', traitPath: null, direction: -1, labels: ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'] }+];++const SCALE_WEIGHT = 0.3;+const CONFIDENCE_BOOST = 0.15;+// =============================================================================// HELPERS// =============================================================================@@ -242,6 +276,91 @@ async function ensureSoulDir() {}}+/**+ * Call any AI provider (API or CLI) with a prompt and return the response text.+ */+async function callProviderAI(provider, model, prompt, { temperature = 0.3, max_tokens = 4000 } = {}) {+ const timeout = provider.timeout || 300000;++ if (provider.type === 'api') {+ const headers = { 'Content-Type': 'application/json' };+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeout);++ const response = await fetch(`${provider.endpoint}/chat/completions`, {+ method: 'POST',+ headers,+ signal: controller.signal,+ body: JSON.stringify({+ model,+ messages: [{ role: 'user', content: prompt }],+ temperature,+ max_tokens+ })+ }).catch((err) => {+ clearTimeout(timer);+ return { ok: false, _fetchError: err.name === 'AbortError' ? 'AI request timed out' : err.message };+ });++ clearTimeout(timer);++ if (response._fetchError) {+ return { error: response._fetchError };+ }++ if (!response.ok) {+ return { error: `Provider API error: ${response.status}` };+ }++ const data = await response.json();+ return { text: data.choices?.[0]?.message?.content || '' };+ }++ // CLI provider — pipe prompt via stdin to avoid arg length limits on large prompts+ const { spawn } = await import('child_process');+ return new Promise((resolve) => {+ const args = [...(provider.args || [])];+ let output = '';+ let resolved = false;++ const child = spawn(provider.command, args, {+ env: { ...process.env, ...provider.envVars },+ shell: false,+ stdio: ['pipe', 'pipe', 'pipe']+ });++ // Pipe prompt via stdin+ child.stdin.write(prompt);+ child.stdin.end();++ child.stdout.on('data', (data) => { output += data.toString(); });+ child.stderr.on('data', (data) => { output += data.toString(); });+ child.on('close', (code) => {+ if (resolved) return;+ resolved = true;+ if (code === 0) {+ resolve({ text: output });+ } else {+ resolve({ error: `CLI exited with code ${code}: ${output.substring(0, 500)}` });+ }+ });+ child.on('error', (err) => {+ if (resolved) return;+ resolved = true;+ resolve({ error: err.message });+ });++ setTimeout(() => {+ if (resolved) return;+ resolved = true;+ child.kill();+ resolve({ error: 'AI request timed out' });+ }, timeout);+ });+}+// =============================================================================// META / SETTINGS// =============================================================================@@ -782,6 +901,26 @@ export async function generateEnrichmentQuestion(category, providerOverride, mod};}+ // Serve unanswered scale questions for this category+ const answered = meta.enrichment.scaleQuestionsAnswered || {};+ const categoryScaleQuestions = SCALE_QUESTIONS.filter(q => q.category === category);+ const unanswered = categoryScaleQuestions.filter(q => !(q.id in answered));+ if (unanswered.length > 0) {+ const sq = unanswered[0];+ return {+ questionId: generateId(),+ category,+ question: sq.text,+ questionType: 'scale',+ labels: sq.labels,+ dimension: sq.dimension,+ scaleQuestionId: sq.id,+ isGenerated: false,+ questionNumber: questionsAnswered + 1,+ totalQuestions: config.questions.length + categoryScaleQuestions.length+ };+ }+// Generate follow-up question using AIconst existingSoul = await getSoulForPrompt({ maxTokens: 2000 });@@ -847,7 +986,123 @@ export async function generateEnrichmentQuestion(category, providerOverride, mod};}+async function processScaleAnswer(data) {+ const { category, question, scaleValue, scaleQuestionId } = data;+ const config = ENRICHMENT_CATEGORIES[category];+ if (!config) throw new Error(`Unknown enrichment category: ${category}`);++ const scaleDef = SCALE_QUESTIONS.find(q => q.id === scaleQuestionId);+ if (!scaleDef) throw new Error(`Unknown scale question: ${scaleQuestionId}`);++ // Convert 1-5 to 0-1, apply direction+ const rawScore = (scaleValue - 1) / 4;+ const adjustedScore = scaleDef.direction === 1 ? rawScore : (1 - rawScore);++ const meta = await loadMeta();+ if (!meta.traits) meta.traits = {};++ // Update trait score via weighted moving average+ if (scaleDef.traitPath) {+ const parts = scaleDef.traitPath.split('.');+ const section = parts[0]; // e.g. 'bigFive' or 'communicationProfile'+ const field = parts[1]; // e.g. 'O' or 'formality'++ if (!meta.traits[section]) meta.traits[section] = {};+ const existing = meta.traits[section][field];++ // communicationProfile fields are integer 1-10+ if (section === 'communicationProfile') {+ const mapped = Math.round(adjustedScore * 9) + 1; // 1-10+ meta.traits[section][field] = existing == null+ ? mapped+ : Math.round(existing * (1 - SCALE_WEIGHT) + mapped * SCALE_WEIGHT);+ } else {+ meta.traits[section][field] = existing == null+ ? Math.round(adjustedScore * 100) / 100+ : Math.round((existing * (1 - SCALE_WEIGHT) + adjustedScore * SCALE_WEIGHT) * 100) / 100;+ }++ meta.traits.lastAnalyzed = now();+ }++ // Boost confidence for the dimension+ if (!meta.confidence) meta.confidence = { overall: 0, dimensions: {}, gaps: [], lastCalculated: now() };+ if (!meta.confidence.dimensions) meta.confidence.dimensions = {};+ const currentConf = meta.confidence.dimensions[scaleDef.dimension] || 0;+ meta.confidence.dimensions[scaleDef.dimension] = Math.min(1, Math.round((currentConf + CONFIDENCE_BOOST) * 100) / 100);++ // Recalculate overall confidence+ const dimValues = Object.values(meta.confidence.dimensions);+ meta.confidence.overall = dimValues.length > 0+ ? Math.round((dimValues.reduce((a, b) => a + b, 0) / dimValues.length) * 100) / 100+ : 0;++ // Regenerate gap recommendations+ meta.confidence.gaps = generateGapRecommendations(meta.confidence.dimensions);+ meta.confidence.lastCalculated = now();++ // Store readable line in target document+ const labelText = scaleDef.labels[scaleValue - 1] || String(scaleValue);+ const formattedContent = `### ${question}\n\nResponse: ${labelText} (${scaleValue}/5)\n\n`;++ await ensureSoulDir();+ const targetPath = join(DIGITAL_TWIN_DIR, config.targetDoc);+ let existingContent = '';+ if (existsSync(targetPath)) {+ existingContent = await readFile(targetPath, 'utf-8');+ } else {+ existingContent = `# ${config.label}\n\n`;+ }+ await writeFile(targetPath, existingContent + '\n' + formattedContent);++ // Record scale answer+ if (!meta.enrichment.scaleQuestionsAnswered) meta.enrichment.scaleQuestionsAnswered = {};+ meta.enrichment.scaleQuestionsAnswered[scaleQuestionId] = scaleValue;++ // Increment questions answered for the category+ if (!meta.enrichment.questionsAnswered) meta.enrichment.questionsAnswered = {};+ meta.enrichment.questionsAnswered[category] = (meta.enrichment.questionsAnswered[category] || 0) + 1;+ meta.enrichment.lastSession = now();++ if (meta.enrichment.questionsAnswered[category] >= 3 &&+ !meta.enrichment.completedCategories.includes(category)) {+ meta.enrichment.completedCategories.push(category);+ }++ // Ensure document is in meta+ const existingDoc = meta.documents.find(d => d.filename === config.targetDoc);+ if (!existingDoc) {+ meta.documents.push({+ id: generateId(),+ filename: config.targetDoc,+ title: config.label,+ category: config.targetCategory || 'enrichment',+ enabled: true,+ priority: 30+ });+ }++ await saveMeta(meta);++ digitalTwinEvents.emit('traits:updated', meta.traits);+ digitalTwinEvents.emit('confidence:calculated', meta.confidence);++ console.log(`📊 Scale answer processed: ${scaleQuestionId}=${scaleValue} → ${scaleDef.dimension} confidence=${meta.confidence.dimensions[scaleDef.dimension]}`);++ return {+ category,+ targetDoc: config.targetDoc,+ contentAdded: formattedContent,+ traitsUpdated: true,+ dimension: scaleDef.dimension,+ newConfidence: meta.confidence.dimensions[scaleDef.dimension]+ };+}+export async function processEnrichmentAnswer(data) {+ // Branch for scale questions+ if (data.questionType === 'scale') return processScaleAnswer(data);+const { category, question, answer, providerOverride, modelOverride } = data;const config = ENRICHMENT_CATEGORIES[category];@@ -1835,6 +2090,9 @@ export async function analyzeTraits(providerId, model, forceReanalyze = false) {await saveMeta(meta);digitalTwinEvents.emit('traits:analyzed', traits);+ // Recalculate confidence with updated traits+ await calculateConfidence();+return { traits, analysisNotes: parsedTraits.analysisNotes };}@@ -1846,16 +2104,18 @@ export async function analyzeTraits(providerId, model, forceReanalyze = false) {function parseTraitsResponse(response) {const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);- if (jsonMatch) {- const parsed = JSON.parse(jsonMatch[1]);- return parsed;+ const jsonStr = jsonMatch ? jsonMatch[1] : (response.trim().startsWith('{') ? response.trim() : null);++ if (!jsonStr) {+ return { error: 'Failed to parse traits response - no JSON found', rawResponse: response };}- if (response.trim().startsWith('{')) {- return JSON.parse(response);+ const parsed = safeJSONParse(jsonStr, null, { allowArray: false });+ if (!parsed) {+ return { error: 'Failed to parse traits response - invalid JSON', rawResponse: response };}- return { error: 'Failed to parse traits response', rawResponse: response };+ return parsed;}/**@@ -2583,6 +2843,102 @@ export async function saveImportAsDocument(source, suggestedDoc) {});}+// =============================================================================+// ASSESSMENT ANALYZER+// =============================================================================++/**+ * Analyze a pasted personality assessment without session management.+ * Extracts traits, creates/updates documents, and returns gap recommendations.+ */+export async function analyzeAssessment(content, providerId, model) {+ console.log(`🧪 [${now()}] Assessment analysis: provider=${providerId}, model=${model}, content=${content.length} chars`);++ // 1. Load twin context+ const twinContent = await getAllTwinContent();+ const meta = await loadMeta();+ const currentTraits = meta.traits || {};+ const confidenceBefore = meta.confidence?.overall || 0;++ // 2. Build analysis prompt+ const analysisPrompt = await buildPrompt('twin-interview-analyze', {+ twinContent: twinContent || 'No existing twin documents yet.',+ currentTraits: JSON.stringify(currentTraits, null, 2) || '{}',+ pastedContent: content+ }).catch(() => null);++ if (!analysisPrompt) {+ return { error: 'Analysis prompt template not found' };+ }++ const provider = await getProviderById(providerId);+ if (!provider || !provider.enabled) {+ return { error: 'Provider not found or disabled' };+ }++ // 3. Call AI for analysis+ console.log(`🧪 [${now()}] Calling ${provider.name} (${model}), prompt=${analysisPrompt.length} chars`);+ const aiResponse = await callProviderAI(provider, model, analysisPrompt, { temperature: 0.3, max_tokens: 4000 });++ if (aiResponse.error) {+ return { error: aiResponse.error };+ }++ const parsed = parseTraitsResponse(aiResponse.text);+ if (parsed.error) {+ return { error: parsed.error };+ }++ // 4. Apply trait updates+ const traitUpdates = {};+ if (parsed.bigFive) traitUpdates.bigFive = parsed.bigFive;+ if (parsed.valuesHierarchy) traitUpdates.valuesHierarchy = parsed.valuesHierarchy;+ if (parsed.communicationProfile) traitUpdates.communicationProfile = parsed.communicationProfile;++ if (Object.keys(traitUpdates).length > 0) {+ await updateTraits(traitUpdates);+ }++ // 5. Create/update documents from suggestions+ const docsCreated = [];+ const docsUpdated = [];+ for (const doc of (parsed.suggestedDocuments || [])) {+ if (!doc.filename || !doc.content) continue;+ const currentMeta = await loadMeta();+ const existsBefore = currentMeta.documents.some(d => d.filename === doc.filename);+ const result = await saveImportAsDocument('interview', {+ filename: doc.filename,+ title: doc.title || doc.filename.replace('.md', ''),+ category: doc.category || 'enrichment',+ content: doc.content+ });+ if (result) {+ (existsBefore ? docsUpdated : docsCreated).push(doc.filename);+ }+ }++ // 6. Recalculate confidence with updated content and traits+ const confidenceResult = await calculateConfidence();+ const confidenceAfter = confidenceResult.confidence?.overall || confidenceBefore;++ // 7. Get gap recommendations+ const gaps = await getGapRecommendations();++ const analysisResult = {+ traitsUpdated: traitUpdates,+ documentsCreated: docsCreated,+ documentsUpdated: docsUpdated,+ newDimensions: parsed.newDimensions || [],+ confidenceDelta: { before: confidenceBefore, after: confidenceAfter },+ summary: parsed.summary || 'Analysis complete. Twin profile updated.'+ };++ digitalTwinEvents.emit('interview:analyzed', { analysisResult });+ console.log(`🧪 [${now()}] Assessment complete: ${docsCreated.length} created, ${docsUpdated.length} updated, ${Object.keys(traitUpdates).length} trait categories`);++ return { analysisResult, gaps };+}+/*** Get list of supported import sources*/