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(digital-twin): add quantitative personality modeling (M34 Phase 1 & 2)

Adam Eivy705e4e0bfd35
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.md
index cb13dc6476..8ae0cf4766 100644
--- a/.changelog/v0.10.x.md
+++ b/.changelog/v0.10.x.md
@@ -87,6 +87,20 @@ This release introduces a structured changelog documentation system for creating
- **Data Directory**: `data/soul/` renamed to `data/digital-twin/`
- **Backwards Compatibility**: Legacy function names and imports aliased for backwards compatibility
+### Digital Twin - Quantitative Personality Modeling (M34 Phase 1 & 2)
+- **Big Five Trait Extraction**: AI-powered analysis extracts OCEAN personality scores (0-1 scale) from digital twin documents with supporting evidence notes
+- **Values Hierarchy**: Automatically extracts and ranks core values with conflict detection between values
+- **Communication Profile**: Quantifies writing style including formality (1-10), verbosity (1-10), emoji usage, preferred tone, and distinctive markers
+- **Confidence Scoring**: Calculates per-dimension confidence scores based on evidence quantity, specificity, and consistency
+- **Gap Recommendations**: Identifies low-confidence dimensions and suggests specific enrichment questions to fill gaps
+- **PersonalityMap Component**: New radar chart visualization showing Big Five traits with confidence-based coloring (green/yellow/red)
+- **ConfidenceGauge Component**: Visual gauge showing overall twin confidence with dimension breakdown and trend indicators
+- **GapRecommendations Component**: Prioritized list of suggested enrichments with urgency labels and specific questions
+- **Prompt Templates**: New `twin-trait-extractor.md` and `twin-confidence-analyzer.md` prompt templates for AI-powered analysis
+- **API Endpoints**: New `/api/digital-twin/traits`, `/api/digital-twin/traits/analyze`, `/api/digital-twin/confidence`, `/api/digital-twin/confidence/calculate`, and `/api/digital-twin/gaps` endpoints
+- **Local Fallback**: Heuristic-based confidence calculation when AI provider is unavailable
+- **Overview Tab Integration**: New components integrated into Digital Twin Overview tab for at-a-glance personality insights
+
### AI Provider Usage Limit Handling & Fallback
- **Usage Limit Detection**: Agents now detect provider usage limit errors (e.g., "You've hit your usage limit. Upgrade to Pro or try again in 1 day 1 hour 33 minutes") and mark providers as temporarily unavailable
- **Provider Status Tracking**: New `providerStatus.js` service tracks provider availability, usage limits, and estimated recovery times with persistence across server restarts
diff --git a/PLAN.md b/PLAN.md
index 77b3cd3137..da741728ca 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -614,3 +614,308 @@ Added 3 new categories with 3 preset questions each:
##### Context Optimization
- **Document Weighting**: Priority slider (1-10) on each document
- Higher weighted documents preserved first when context limits force truncation
+
+---
+
+## M34: Digital Twin Personality Enhancement
+
+### Vision
+
+Transform the Digital Twin from a **document capture system** into a **quantitative personality modeling and prediction system** that can accurately embody a human's values, decision patterns, and communication style.
+
+### Current State Assessment
+
+| Strength | Gap |
+|----------|-----|
+| Rich document storage (14 categories) | No quantitative personality dimensions |
+| Multi-method enrichment | No automated extraction from behavior |
+| Behavioral testing framework | No feedback loop from real usage |
+| Writing sample analysis | No multi-modal capture (voice, video) |
+| Contradiction detection | No personality confidence scoring |
+| CoS integration | No external data source integration |
+
+### Improvement Phases
+
+#### Phase 1: Quantitative Personality Modeling (Foundation)
+
+**Goal**: Add structured personality trait scoring alongside unstructured documents.
+
+**1.1 Big Five Trait Scoring**
+- Add quantified OCEAN scores (Openness, Conscientiousness, Extraversion, Agreeableness, Neuroticism)
+- Infer scores from existing documents using LLM analysis
+- Allow manual override/adjustment
+- Store in `meta.json` under `traits.bigFive`
+
+**1.2 Values Hierarchy**
+- Extract explicit values from VALUES.md and NON_NEGOTIABLES.md
+- Create ranked values list with conflict resolution rules
+- Store in `meta.json` under `traits.valuesHierarchy`
+
+**1.3 Communication Fingerprint**
+- Quantify writing style: formality (1-10), verbosity (1-10), emoji usage, sentence length avg
+- Extract from WRITING_STYLE.md and writing samples
+- Store in `meta.json` under `traits.communicationProfile`
+
+**Data Structure**:
+```javascript
+traits: {
+ bigFive: { O: 0.75, C: 0.82, E: 0.45, A: 0.68, N: 0.32 },
+ valuesHierarchy: ["authenticity", "growth", "family", ...],
+ communicationProfile: {
+ formality: 6,
+ verbosity: 4,
+ avgSentenceLength: 18,
+ emojiUsage: "rare",
+ preferredTone: "direct-but-warm"
+ },
+ lastAnalyzed: "2026-01-21T..."
+}
+```
+
+**API Endpoints**:
+| Route | Description |
+|-------|-------------|
+| GET /api/digital-twin/traits | Get all trait scores |
+| POST /api/digital-twin/traits/analyze | Analyze documents → extract traits |
+| PUT /api/digital-twin/traits/:category | Manual override trait scores |
+
+---
+
+#### Phase 2: Personality Confidence Scoring
+
+**Goal**: Measure how well-defined each aspect of personality is, guiding enrichment.
+
+**2.1 Coverage Metrics**
+- For each Big Five dimension: evidence count from documents
+- For each value: supporting document count + specificity score
+- For communication: sample diversity, consistency across samples
+
+**2.2 Confidence Algorithm**
+```
+confidence(aspect) = min(1.0,
+ (evidence_count / required_evidence) *
+ (consistency_score) *
+ (recency_weight)
+)
+```
+
+**2.3 Gap Recommendations**
+- Identify lowest-confidence aspects
+- Generate specific questions to fill gaps
+- Prioritize enrichment categories by confidence gap
+
+**UI Enhancement**:
+- Add "Personality Map" visualization showing confidence per dimension
+- Color-code: green (>80%), yellow (50-80%), red (<50%)
+- Click dimension → suggested enrichment questions
+
+---
+
+#### Phase 3: Behavioral Feedback Loop
+
+**Goal**: Learn from real-world twin usage to improve accuracy.
+
+**3.1 Response Validation Interface**
+- When CoS uses twin context, log the interaction
+- User can mark responses: "sounds like me" / "not quite me" / "definitely not me"
+- Store feedback in `data/digital-twin/feedback.json`
+
+**3.2 Feedback Analysis**
+- Periodically analyze feedback patterns
+- Identify which aspects of twin are underperforming
+- Generate document improvement suggestions
+
+**3.3 Adaptive Weighting**
+- Documents that correlate with "sounds like me" responses → increase weight
+- Documents that correlate with misses → flag for review
+- Auto-adjust document weights based on feedback patterns
+
+**Data Structure**:
+```javascript
+feedback: [
+ {
+ id: "uuid",
+ timestamp: "...",
+ context: "summary of interaction",
+ response: "what the twin said",
+ rating: "sounds_like_me" | "not_quite" | "definitely_not",
+ documentsUsed: ["doc-id-1", "doc-id-2"],
+ traits: { /* which traits were relevant */ }
+ }
+]
+```
+
+---
+
+#### Phase 4: External Data Integration
+
+**Goal**: Reduce manual input by importing from external sources.
+
+**4.1 Reading List Import**
+- Goodreads CSV import → analyze for personality insights
+- Extract: genres preferred, themes that resonate, reading patterns
+
+**4.2 Music Profile Import**
+- Spotify listening history → infer emotional patterns, energy levels
+- Last.fm scrobbles → genre preferences, listening habits
+
+**4.3 Social Media Analysis (Optional)**
+- Twitter/X export → communication style, topics of interest
+- LinkedIn export → professional values, career trajectory
+
+**4.4 Calendar Pattern Analysis**
+- iCal export → routine patterns, priorities by time allocation
+- Meeting patterns → social preferences
+
+**Implementation Notes**:
+- All imports are user-initiated, explicit consent
+- Data processed locally, not stored raw
+- Only personality inferences stored, not source data
+
+---
+
+#### Phase 5: Multi-Modal Personality Capture
+
+**Goal**: Capture personality from voice and video, not just text.
+
+**5.1 Voice Analysis**
+- Record voice samples describing self
+- Extract: speech pace, pitch variation, pause patterns
+- Infer: confidence level, emotional expressiveness
+
+**5.2 Video Interview**
+- Guided self-interview with webcam
+- Analyze: facial expressions, gestures, eye contact patterns
+- Generate insights about authentic presentation vs stated identity
+
+**5.3 Audio Transcript Enrichment**
+- Transcribe voice samples → analyze as writing samples
+- Compare spoken vs written style differences
+
+**Technical Approach**:
+- Use Whisper for transcription
+- Use open-source models for facial expression analysis
+- Store only derived insights, not raw recordings
+
+---
+
+#### Phase 6: Advanced Behavioral Testing
+
+**Goal**: More sophisticated twin validation beyond Q&A tests.
+
+**6.1 Scenario Simulation Tests**
+- Complex multi-turn conversations
+- Role-play scenarios (negotiation, conflict, mentoring)
+- Evaluate: consistency across turns, appropriate boundary-setting
+
+**6.2 Ethical Dilemma Tests**
+- Present moral dilemmas aligned with stated values
+- Check if twin's reasoning matches user's value hierarchy
+- Detect values actually held vs values aspired to
+
+**6.3 Communication Style Tests**
+- Generate responses, measure against communication fingerprint
+- Check: formality match, verbosity match, tone match
+- Quantitative scoring instead of pass/fail
+
+**6.4 Adversarial Testing**
+- Prompts designed to elicit non-me responses
+- Check if twin maintains boundaries (error_intolerance)
+- Verify non-negotiables are enforced
+
+---
+
+#### Phase 7: Twin Personas & Context Switching
+
+**Goal**: Support multiple personality variants for different contexts.
+
+**7.1 Persona System**
+- Create named personas (Professional, Casual, Family, Creative)
+- Each persona: subset of documents + weight overrides
+- Context-aware persona selection
+
+**7.2 Blending Rules**
+- Define which traits change per persona vs remain constant
+- Example: formality varies, core values stay constant
+
+**7.3 Persona Testing**
+- Test each persona independently
+- Ensure personas don't violate core identity boundaries
+
+---
+
+### Implementation Priority
+
+| Phase | Priority | Complexity | Impact |
+|-------|----------|------------|--------|
+| P1: Quantitative Modeling | HIGH | Medium | High - enables all other phases |
+| P2: Confidence Scoring | HIGH | Low | High - guides enrichment |
+| P3: Feedback Loop | HIGH | Medium | Very High - enables learning |
+| P4: External Integration | MEDIUM | High | Medium - convenience |
+| P5: Multi-Modal | LOW | Very High | Medium - nice to have |
+| P6: Advanced Testing | MEDIUM | Medium | High - validation quality |
+| P7: Personas | LOW | Medium | Medium - power users |
+
+### Recommended Starting Point
+
+**Phase 1.1 + 2.1 + 2.3** as single implementation:
+1. Add Big Five trait analysis from existing documents
+2. Add confidence scoring per dimension
+3. Add gap recommendations in UI
+
+This provides immediate value by making the enrichment process more guided and measurable.
+
+### Success Metrics
+
+| Metric | Current | Target |
+|--------|---------|--------|
+| Behavioral test pass rate | ~70% | >90% |
+| Enrichment category coverage | Manual | Confidence-guided |
+| User feedback: "sounds like me" | N/A | >85% |
+| Time to usable twin | Hours | <30 min |
+| Trait confidence coverage | 0% | >80% across all dimensions |
+
+---
+
+### Technical Considerations
+
+**New Prompt Templates Needed**:
+- `twin-trait-extractor` - Analyze documents → Big Five scores
+- `twin-values-ranker` - Extract and rank values with conflict rules
+- `twin-confidence-analyzer` - Score document evidence per dimension
+- `twin-feedback-analyzer` - Learn from usage feedback patterns
+- `twin-scenario-generator` - Create multi-turn test scenarios
+- `twin-dilemma-generator` - Create ethical dilemma tests
+
+**Schema Extensions** (`lib/digitalTwinValidation.js`):
+```javascript
+traitsSchema = z.object({
+ bigFive: z.object({
+ O: z.number().min(0).max(1),
+ C: z.number().min(0).max(1),
+ E: z.number().min(0).max(1),
+ A: z.number().min(0).max(1),
+ N: z.number().min(0).max(1)
+ }).optional(),
+ valuesHierarchy: z.array(z.string()).optional(),
+ communicationProfile: communicationProfileSchema.optional(),
+ lastAnalyzed: z.string().datetime().optional()
+});
+
+confidenceSchema = z.object({
+ overall: z.number().min(0).max(1),
+ dimensions: z.record(z.string(), z.number().min(0).max(1)),
+ gaps: z.array(z.object({
+ dimension: z.string(),
+ confidence: z.number(),
+ suggestedQuestions: z.array(z.string())
+ }))
+});
+```
+
+**New UI Components**:
+- `PersonalityMap.jsx` - Radar chart of Big Five + confidence coloring
+- `ConfidenceGauge.jsx` - Per-dimension confidence indicator
+- `FeedbackRater.jsx` - "Sounds like me" rating interface
+- `GapRecommendations.jsx` - Prioritized enrichment suggestions
+- `TraitEditor.jsx` - Manual trait override interface
diff --git a/client/src/components/digital-twin/ConfidenceGauge.jsx b/client/src/components/digital-twin/ConfidenceGauge.jsx
new file mode 100644
index 0000000000..be99f0d679
--- /dev/null
+++ b/client/src/components/digital-twin/ConfidenceGauge.jsx
@@ -0,0 +1,212 @@
+import { useState } from 'react';
+import { Gauge, RefreshCw, TrendingUp, TrendingDown } from 'lucide-react';
+import * as api from '../../services/api';
+import toast from 'react-hot-toast';
+
+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'
+};
+
+const DIMENSION_ICONS = {
+ openness: '🎨',
+ conscientiousness: '📋',
+ extraversion: '👥',
+ agreeableness: '🤝',
+ neuroticism: '💭',
+ values: '⭐',
+ communication: '💬',
+ decision_making: '🎯',
+ boundaries: '🛡️',
+ identity: '🪪'
+};
+
+function getConfidenceColor(score) {
+ if (score >= 0.8) return { text: 'text-green-400', bg: 'bg-green-500', border: 'border-green-500/30' };
+ if (score >= 0.6) return { text: 'text-yellow-400', bg: 'bg-yellow-500', border: 'border-yellow-500/30' };
+ return { text: 'text-red-400', bg: 'bg-red-500', border: 'border-red-500/30' };
+}
+
+function getConfidenceLabel(score) {
+ if (score >= 0.8) return 'Strong';
+ if (score >= 0.6) return 'Moderate';
+ return 'Needs Work';
+}
+
+export default function ConfidenceGauge({ confidence, onRecalculate }) {
+ const [calculating, setCalculating] = useState(false);
+ const [showAll, setShowAll] = useState(false);
+
+ const handleRecalculate = async () => {
+ setCalculating(true);
+ const result = await api.calculateDigitalTwinConfidence().catch(e => ({ error: e.message }));
+ if (result.error) {
+ toast.error(result.error);
+ } else {
+ toast.success('Confidence recalculated');
+ onRecalculate?.();
+ }
+ setCalculating(false);
+ };
+
+ const overall = confidence?.overall ?? 0;
+ const dimensions = confidence?.dimensions ?? {};
+ const overallColor = getConfidenceColor(overall);
+
+ // Sort dimensions by score (lowest first for attention)
+ const sortedDimensions = Object.entries(dimensions)
+ .sort((a, b) => a[1] - b[1]);
+
+ const displayDimensions = showAll ? sortedDimensions : sortedDimensions.slice(0, 5);
+
+ return (
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <div className="flex items-center justify-between mb-4">
+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">
+ <Gauge size={20} />
+ Twin Confidence
+ </h2>
+ <button
+ onClick={handleRecalculate}
+ disabled={calculating}
+ className="text-sm text-port-accent hover:text-white transition-colors flex items-center gap-1"
+ >
+ {calculating ? (
+ <>
+ <RefreshCw className="w-3 h-3 animate-spin" />
+ Calculating...
+ </>
+ ) : (
+ 'Recalculate'
+ )}
+ </button>
+ </div>
+
+ {/* Overall Score */}
+ <div className="flex items-center gap-6 mb-6">
+ <div className="relative w-24 h-24 flex-shrink-0">
+ <svg className="w-full h-full transform -rotate-90" viewBox="0 0 100 100">
+ <circle
+ cx="50"
+ cy="50"
+ r="40"
+ stroke="currentColor"
+ strokeWidth="8"
+ fill="none"
+ className="text-port-border"
+ />
+ <circle
+ cx="50"
+ cy="50"
+ r="40"
+ stroke="currentColor"
+ strokeWidth="8"
+ fill="none"
+ strokeDasharray={`${overall * 251.2} 251.2`}
+ strokeLinecap="round"
+ className={overallColor.text}
+ />
+ </svg>
+ <div className="absolute inset-0 flex flex-col items-center justify-center">
+ <span className={`text-xl font-bold ${overallColor.text}`}>
+ {Math.round(overall * 100)}%
+ </span>
+ </div>
+ </div>
+
+ <div className="flex-1">
+ <div className={`text-lg font-semibold ${overallColor.text}`}>
+ {getConfidenceLabel(overall)}
+ </div>
+ <p className="text-sm text-gray-400 mt-1">
+ {overall >= 0.8
+ ? 'Your digital twin is well-defined and ready for use.'
+ : overall >= 0.6
+ ? 'Good foundation, but some areas need more detail.'
+ : 'More enrichment needed for accurate personality modeling.'}
+ </p>
+ {confidence?.lastCalculated && (
+ <p className="text-xs text-gray-500 mt-2">
+ Last calculated: {new Date(confidence.lastCalculated).toLocaleString()}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Dimension Breakdown */}
+ <div className="space-y-2">
+ <div className="flex items-center justify-between text-sm text-gray-400 mb-2">
+ <span>Dimensions</span>
+ <button
+ onClick={() => setShowAll(!showAll)}
+ className="text-port-accent hover:text-white transition-colors"
+ >
+ {showAll ? 'Show Less' : `Show All (${sortedDimensions.length})`}
+ </button>
+ </div>
+
+ {displayDimensions.map(([dimension, score]) => {
+ const color = getConfidenceColor(score);
+ const label = DIMENSION_LABELS[dimension] || dimension;
+ const icon = DIMENSION_ICONS[dimension] || '📊';
+ const isLow = score < 0.6;
+
+ return (
+ <div
+ key={dimension}
+ className={`flex items-center gap-3 p-2 rounded-lg ${
+ isLow ? 'bg-red-500/5 border border-red-500/20' : ''
+ }`}
+ >
+ <span className="text-lg">{icon}</span>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between">
+ <span className="text-sm text-white truncate">{label}</span>
+ <span className={`text-sm font-medium ${color.text}`}>
+ {Math.round(score * 100)}%
+ </span>
+ </div>
+ <div className="h-1.5 bg-port-border rounded-full overflow-hidden mt-1">
+ <div
+ className={`h-full transition-all ${color.bg}`}
+ style={{ width: `${score * 100}%` }}
+ />
+ </div>
+ </div>
+ {isLow && (
+ <TrendingDown className="w-4 h-4 text-red-400 flex-shrink-0" />
+ )}
+ {score >= 0.8 && (
+ <TrendingUp className="w-4 h-4 text-green-400 flex-shrink-0" />
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Legend */}
+ <div className="flex items-center gap-4 mt-4 pt-4 border-t border-port-border text-xs">
+ <div className="flex items-center gap-1">
+ <div className="w-2 h-2 rounded-full bg-green-500" />
+ <span className="text-gray-400">Strong (80%+)</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <div className="w-2 h-2 rounded-full bg-yellow-500" />
+ <span className="text-gray-400">Moderate (60-79%)</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <div className="w-2 h-2 rounded-full bg-red-500" />
+ <span className="text-gray-400">Needs Work (&lt;60%)</span>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/digital-twin/GapRecommendations.jsx b/client/src/components/digital-twin/GapRecommendations.jsx
new file mode 100644
index 0000000000..357639f5fd
--- /dev/null
+++ b/client/src/components/digital-twin/GapRecommendations.jsx
@@ -0,0 +1,162 @@
+import { useNavigate } from 'react-router-dom';
+import { Lightbulb, ChevronRight, MessageCircle, ArrowRight } from 'lucide-react';
+
+const CATEGORY_LABELS = {
+ core_memories: 'Core Memories',
+ favorite_books: 'Favorite Books',
+ favorite_movies: 'Favorite Movies',
+ music_taste: 'Music Taste',
+ communication: 'Communication',
+ decision_making: 'Decision Making',
+ values: 'Values',
+ aesthetics: 'Aesthetics',
+ daily_routines: 'Daily Routines',
+ career_skills: 'Career/Skills',
+ non_negotiables: 'Non-Negotiables',
+ decision_heuristics: 'Decision Heuristics',
+ error_intolerance: 'Error Intolerance',
+ personality_assessments: 'Personality Assessments'
+};
+
+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 getUrgencyColor(confidence) {
+ if (confidence < 0.3) return 'border-red-500/50 bg-red-500/10';
+ if (confidence < 0.5) return 'border-orange-500/50 bg-orange-500/10';
+ return 'border-yellow-500/50 bg-yellow-500/10';
+}
+
+function getUrgencyLabel(confidence) {
+ if (confidence < 0.3) return { text: 'Critical', color: 'text-red-400' };
+ if (confidence < 0.5) return { text: 'Important', color: 'text-orange-400' };
+ return { text: 'Suggested', color: 'text-yellow-400' };
+}
+
+export default function GapRecommendations({ gaps, maxDisplay = 3 }) {
+ const navigate = useNavigate();
+
+ if (!gaps || gaps.length === 0) {
+ return (
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <div className="flex items-center gap-2 mb-4">
+ <Lightbulb size={20} className="text-green-400" />
+ <h2 className="text-lg font-semibold text-white">Enrichment Complete!</h2>
+ </div>
+ <p className="text-gray-400">
+ Your digital twin has strong confidence across all dimensions.
+ Consider running behavioral tests to validate accuracy.
+ </p>
+ <button
+ onClick={() => navigate('/digital-twin/test')}
+ className="mt-4 px-4 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 flex items-center gap-2"
+ >
+ Run Tests
+ <ArrowRight size={16} />
+ </button>
+ </div>
+ );
+ }
+
+ const displayGaps = gaps.slice(0, maxDisplay);
+ const hasMore = gaps.length > maxDisplay;
+
+ return (
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <div className="flex items-center justify-between mb-4">
+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">
+ <Lightbulb size={20} className="text-yellow-400" />
+ Recommended Enrichment
+ </h2>
+ {hasMore && (
+ <span className="text-sm text-gray-400">
+ +{gaps.length - maxDisplay} more
+ </span>
+ )}
+ </div>
+
+ <p className="text-sm text-gray-400 mb-4">
+ These areas need more detail for accurate personality modeling.
+ </p>
+
+ <div className="space-y-3">
+ {displayGaps.map((gap, index) => {
+ const urgency = getUrgencyLabel(gap.confidence);
+ const dimensionLabel = DIMENSION_LABELS[gap.dimension] || gap.dimension;
+ const categoryLabel = CATEGORY_LABELS[gap.suggestedCategory] || gap.suggestedCategory;
+
+ return (
+ <div
+ key={gap.dimension}
+ className={`p-4 rounded-lg border ${getUrgencyColor(gap.confidence)}`}
+ >
+ <div className="flex items-start justify-between mb-2">
+ <div>
+ <div className="flex items-center gap-2">
+ <span className="text-white font-medium">{dimensionLabel}</span>
+ <span className={`text-xs px-2 py-0.5 rounded-full ${urgency.color} bg-black/20`}>
+ {urgency.text}
+ </span>
+ </div>
+ <div className="text-xs text-gray-500 mt-1">
+ {gap.evidenceCount}/{gap.requiredEvidence} evidence points • {Math.round(gap.confidence * 100)}% confidence
+ </div>
+ </div>
+ <button
+ onClick={() => navigate('/digital-twin/enrich')}
+ className="flex items-center gap-1 text-sm text-port-accent hover:text-white transition-colors"
+ >
+ Enrich
+ <ChevronRight size={14} />
+ </button>
+ </div>
+
+ {gap.suggestedQuestions && gap.suggestedQuestions.length > 0 && (
+ <div className="mt-3 space-y-2">
+ <div className="text-xs text-gray-400 flex items-center gap-1">
+ <MessageCircle size={12} />
+ Suggested questions:
+ </div>
+ <ul className="space-y-1">
+ {gap.suggestedQuestions.slice(0, 2).map((question, qi) => (
+ <li
+ key={qi}
+ className="text-sm text-gray-300 pl-4 border-l border-port-border"
+ >
+ "{question}"
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {gap.suggestedCategory && (
+ <div className="mt-2 text-xs text-gray-500">
+ Best enrichment category: <span className="text-gray-400">{categoryLabel}</span>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ <button
+ onClick={() => navigate('/digital-twin/enrich')}
+ className="w-full mt-4 px-4 py-3 bg-port-accent/20 border border-port-accent/50 text-port-accent rounded-lg text-sm hover:bg-port-accent/30 transition-colors flex items-center justify-center gap-2"
+ >
+ Start Enrichment Session
+ <ArrowRight size={16} />
+ </button>
+ </div>
+ );
+}
diff --git a/client/src/components/digital-twin/PersonalityMap.jsx b/client/src/components/digital-twin/PersonalityMap.jsx
new file mode 100644
index 0000000000..42f6dd2c46
--- /dev/null
+++ b/client/src/components/digital-twin/PersonalityMap.jsx
@@ -0,0 +1,316 @@
+import { useState } from 'react';
+import { Brain, RefreshCw, AlertCircle } from 'lucide-react';
+import * as api from '../../services/api';
+import toast from 'react-hot-toast';
+
+const BIG_FIVE_LABELS = {
+ O: { name: 'Openness', low: 'Practical', high: 'Curious' },
+ C: { name: 'Conscientiousness', low: 'Flexible', high: 'Organized' },
+ E: { name: 'Extraversion', low: 'Reserved', high: 'Outgoing' },
+ A: { name: 'Agreeableness', low: 'Analytical', high: 'Empathetic' },
+ N: { name: 'Neuroticism', low: 'Stable', high: 'Sensitive' }
+};
+
+const TRAIT_ORDER = ['O', 'C', 'E', 'A', 'N'];
+
+function getConfidenceColor(confidence) {
+ if (confidence >= 0.8) return 'text-green-400';
+ if (confidence >= 0.6) return 'text-yellow-400';
+ return 'text-red-400';
+}
+
+function getConfidenceBg(confidence) {
+ if (confidence >= 0.8) return 'bg-green-500';
+ if (confidence >= 0.6) return 'bg-yellow-500';
+ return 'bg-red-500';
+}
+
+export default function PersonalityMap({ traits, confidence, providers, onAnalyze }) {
+ const [analyzing, setAnalyzing] = useState(false);
+ const [selectedProvider, setSelectedProvider] = useState(
+ providers?.[0] ? { providerId: providers[0].id, model: providers[0].defaultModel } : null
+ );
+ const [showDetails, setShowDetails] = useState(false);
+
+ const handleAnalyze = async () => {
+ if (!selectedProvider) {
+ toast.error('Select a provider first');
+ return;
+ }
+ setAnalyzing(true);
+ const result = await api.analyzeDigitalTwinTraits(
+ selectedProvider.providerId,
+ selectedProvider.model,
+ true
+ ).catch(e => ({ error: e.message }));
+
+ if (result.error) {
+ toast.error(result.error);
+ } else {
+ toast.success('Traits analyzed successfully');
+ onAnalyze?.();
+ }
+ setAnalyzing(false);
+ };
+
+ const bigFive = traits?.bigFive;
+ const hasTraits = bigFive && Object.keys(bigFive).length > 0;
+
+ // Get dimension confidence from confidence object
+ const getDimensionConfidence = (trait) => {
+ const dimensionMap = {
+ O: 'openness',
+ C: 'conscientiousness',
+ E: 'extraversion',
+ A: 'agreeableness',
+ N: 'neuroticism'
+ };
+ return confidence?.dimensions?.[dimensionMap[trait]] ?? 0.5;
+ };
+
+ // Radar chart calculations
+ const centerX = 100;
+ const centerY = 100;
+ const maxRadius = 80;
+ const levels = 5;
+
+ const getPoint = (index, value) => {
+ const angle = (Math.PI * 2 * index) / 5 - Math.PI / 2;
+ const radius = maxRadius * value;
+ return {
+ x: centerX + radius * Math.cos(angle),
+ y: centerY + radius * Math.sin(angle)
+ };
+ };
+
+ const radarPoints = hasTraits
+ ? TRAIT_ORDER.map((trait, i) => getPoint(i, bigFive[trait] || 0.5))
+ : TRAIT_ORDER.map((_, i) => getPoint(i, 0.5));
+
+ const radarPath = radarPoints.map((p, i) =>
+ `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`
+ ).join(' ') + ' Z';
+
+ return (
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <div className="flex items-center justify-between mb-4">
+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">
+ <Brain size={20} />
+ Personality Traits
+ </h2>
+ <button
+ onClick={() => setShowDetails(!showDetails)}
+ className="text-sm text-port-accent hover:text-white transition-colors"
+ >
+ {showDetails ? 'Hide Details' : 'Show Details'}
+ </button>
+ </div>
+
+ {!hasTraits ? (
+ <div className="text-center py-8">
+ <AlertCircle className="w-12 h-12 text-gray-500 mx-auto mb-4" />
+ <p className="text-gray-400 mb-4">
+ No personality traits analyzed yet. Run an analysis to extract Big Five traits from your documents.
+ </p>
+ <div className="flex flex-col sm:flex-row items-center justify-center gap-3">
+ <select
+ value={selectedProvider ? `${selectedProvider.providerId}:${selectedProvider.model}` : ''}
+ onChange={(e) => {
+ const [providerId, model] = e.target.value.split(':');
+ setSelectedProvider({ providerId, model });
+ }}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-w-[200px]"
+ >
+ {providers?.map(p => (
+ (p.models || [p.defaultModel]).filter(Boolean).map(model => (
+ <option key={`${p.id}:${model}`} value={`${p.id}:${model}`}>
+ {p.name} - {model}
+ </option>
+ ))
+ ))}
+ </select>
+ <button
+ onClick={handleAnalyze}
+ disabled={analyzing}
+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 disabled:opacity-50 flex items-center gap-2"
+ >
+ {analyzing ? (
+ <>
+ <RefreshCw className="w-4 h-4 animate-spin" />
+ Analyzing...
+ </>
+ ) : (
+ 'Analyze Traits'
+ )}
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col lg:flex-row gap-6">
+ {/* Radar Chart */}
+ <div className="flex-shrink-0 mx-auto lg:mx-0">
+ <svg width="200" height="200" viewBox="0 0 200 200" className="overflow-visible">
+ {/* Background levels */}
+ {Array.from({ length: levels }).map((_, i) => {
+ const levelRadius = (maxRadius / levels) * (i + 1);
+ const levelPoints = TRAIT_ORDER.map((_, j) => {
+ const angle = (Math.PI * 2 * j) / 5 - Math.PI / 2;
+ return {
+ x: centerX + levelRadius * Math.cos(angle),
+ y: centerY + levelRadius * Math.sin(angle)
+ };
+ });
+ const path = levelPoints.map((p, j) =>
+ `${j === 0 ? 'M' : 'L'} ${p.x} ${p.y}`
+ ).join(' ') + ' Z';
+ return (
+ <path
+ key={i}
+ d={path}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1"
+ className="text-port-border"
+ opacity={0.3}
+ />
+ );
+ })}
+
+ {/* Axis lines */}
+ {TRAIT_ORDER.map((_, i) => {
+ const angle = (Math.PI * 2 * i) / 5 - Math.PI / 2;
+ const endX = centerX + maxRadius * Math.cos(angle);
+ const endY = centerY + maxRadius * Math.sin(angle);
+ return (
+ <line
+ key={i}
+ x1={centerX}
+ y1={centerY}
+ x2={endX}
+ y2={endY}
+ stroke="currentColor"
+ strokeWidth="1"
+ className="text-port-border"
+ opacity={0.3}
+ />
+ );
+ })}
+
+ {/* Data polygon */}
+ <path
+ d={radarPath}
+ fill="currentColor"
+ fillOpacity="0.3"
+ stroke="currentColor"
+ strokeWidth="2"
+ className="text-port-accent"
+ />
+
+ {/* Data points */}
+ {radarPoints.map((point, i) => {
+ const traitConfidence = getDimensionConfidence(TRAIT_ORDER[i]);
+ return (
+ <circle
+ key={i}
+ cx={point.x}
+ cy={point.y}
+ r="5"
+ className={getConfidenceBg(traitConfidence)}
+ />
+ );
+ })}
+
+ {/* Labels */}
+ {TRAIT_ORDER.map((trait, i) => {
+ const angle = (Math.PI * 2 * i) / 5 - Math.PI / 2;
+ const labelRadius = maxRadius + 20;
+ const x = centerX + labelRadius * Math.cos(angle);
+ const y = centerY + labelRadius * Math.sin(angle);
+ const value = bigFive[trait] || 0.5;
+ const traitConfidence = getDimensionConfidence(trait);
+ return (
+ <g key={trait}>
+ <text
+ x={x}
+ y={y}
+ textAnchor="middle"
+ dominantBaseline="middle"
+ className={`text-xs font-medium fill-current ${getConfidenceColor(traitConfidence)}`}
+ >
+ {trait}
+ </text>
+ <text
+ x={x}
+ y={y + 12}
+ textAnchor="middle"
+ dominantBaseline="middle"
+ className="text-xs fill-current text-gray-500"
+ >
+ {Math.round(value * 100)}%
+ </text>
+ </g>
+ );
+ })}
+ </svg>
+ </div>
+
+ {/* Trait Details */}
+ <div className="flex-1 space-y-3">
+ {TRAIT_ORDER.map(trait => {
+ const value = bigFive[trait] || 0.5;
+ const traitConfidence = getDimensionConfidence(trait);
+ const label = BIG_FIVE_LABELS[trait];
+ return (
+ <div key={trait} className="space-y-1">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-white">{label.name}</span>
+ <span className={`text-sm ${getConfidenceColor(traitConfidence)}`}>
+ {Math.round(value * 100)}%
+ </span>
+ </div>
+ <div className="h-2 bg-port-border rounded-full overflow-hidden">
+ <div
+ className={`h-full transition-all ${getConfidenceBg(traitConfidence)}`}
+ style={{ width: `${value * 100}%`, opacity: 0.7 + (traitConfidence * 0.3) }}
+ />
+ </div>
+ <div className="flex justify-between text-xs text-gray-500">
+ <span>{label.low}</span>
+ <span>{label.high}</span>
+ </div>
+ </div>
+ );
+ })}
+
+ {showDetails && (
+ <div className="mt-4 pt-4 border-t border-port-border">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-sm text-gray-400">Last analyzed</span>
+ <span className="text-sm text-white">
+ {traits.lastAnalyzed
+ ? new Date(traits.lastAnalyzed).toLocaleDateString()
+ : 'Never'}
+ </span>
+ </div>
+ <button
+ onClick={handleAnalyze}
+ disabled={analyzing}
+ className="w-full mt-2 px-4 py-2 bg-port-bg border border-port-border text-white rounded-lg text-sm hover:bg-port-border disabled:opacity-50 flex items-center justify-center gap-2"
+ >
+ {analyzing ? (
+ <>
+ <RefreshCw className="w-4 h-4 animate-spin" />
+ Reanalyzing...
+ </>
+ ) : (
+ 'Reanalyze Traits'
+ )}
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/digital-twin/tabs/OverviewTab.jsx b/client/src/components/digital-twin/tabs/OverviewTab.jsx
index 4e4fe04387..303a4f58f9 100644
--- a/client/src/components/digital-twin/tabs/OverviewTab.jsx
+++ b/client/src/components/digital-twin/tabs/OverviewTab.jsx
@@ -24,6 +24,9 @@ import {
formatRelativeTime
} from '../constants';
import SoulWizard from '../SoulWizard';
+import PersonalityMap from '../PersonalityMap';
+import ConfidenceGauge from '../ConfidenceGauge';
+import GapRecommendations from '../GapRecommendations';
export default function OverviewTab({ status, settings, onRefresh }) {
const navigate = useNavigate();
@@ -38,12 +41,27 @@ export default function OverviewTab({ status, settings, onRefresh }) {
const [providers, setProviders] = useState([]);
const [selectedProvider, setSelectedProvider] = useState(null);
const [showWizard, setShowWizard] = useState(false);
+ const [traits, setTraits] = useState(null);
+ const [confidence, setConfidence] = useState(null);
+ const [gaps, setGaps] = useState([]);
useEffect(() => {
loadCompleteness();
loadProviders();
+ loadTraitsAndConfidence();
}, []);
+ const loadTraitsAndConfidence = async () => {
+ const [traitsData, confidenceData, gapsData] = await Promise.all([
+ api.getDigitalTwinTraits().catch(() => ({ traits: null })),
+ api.getDigitalTwinConfidence().catch(() => ({ confidence: null })),
+ api.getDigitalTwinGaps().catch(() => ({ gaps: [] }))
+ ]);
+ setTraits(traitsData.traits);
+ setConfidence(confidenceData.confidence);
+ setGaps(gapsData.gaps || []);
+ };
+
const loadCompleteness = async () => {
setLoadingCompleteness(true);
const data = await api.getSoulCompleteness().catch(() => null);
@@ -256,6 +274,25 @@ export default function OverviewTab({ status, settings, onRefresh }) {
)}
</div>
+ {/* Personality Traits & Confidence - New Phase 1 & 2 Components */}
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ <PersonalityMap
+ traits={traits}
+ confidence={confidence}
+ providers={providers}
+ onAnalyze={loadTraitsAndConfidence}
+ />
+ <ConfidenceGauge
+ confidence={confidence}
+ onRecalculate={loadTraitsAndConfidence}
+ />
+ </div>
+
+ {/* Gap Recommendations */}
+ {gaps.length > 0 && (
+ <GapRecommendations gaps={gaps} maxDisplay={3} />
+ )}
+
{/* Completeness Score */}
<div className="bg-port-card rounded-lg border border-port-border p-6">
<div className="flex items-center justify-between mb-4">
diff --git a/client/src/services/api.js b/client/src/services/api.js
index b190b3a134..0bc29b3772 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -648,6 +648,23 @@ export const saveEnrichmentList = (category, content, items) => request('/digita
});
export const getEnrichmentListItems = (category) => request(`/digital-twin/enrich/list-items/${category}`);
+// --- Digital Twin Traits & Confidence (Phase 1 & 2) ---
+export const getDigitalTwinTraits = () => request('/digital-twin/traits');
+export const analyzeDigitalTwinTraits = (providerId, model, forceReanalyze = false) => request('/digital-twin/traits/analyze', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model, forceReanalyze })
+});
+export const updateDigitalTwinTraits = (updates) => request('/digital-twin/traits', {
+ method: 'PUT',
+ body: JSON.stringify(updates)
+});
+export const getDigitalTwinConfidence = () => request('/digital-twin/confidence');
+export const calculateDigitalTwinConfidence = (providerId, model) => request('/digital-twin/confidence/calculate', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model })
+});
+export const getDigitalTwinGaps = () => request('/digital-twin/gaps');
+
// Default export for simplified imports
export default {
get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index 401a938c8e..f6047864c5 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -88,13 +88,79 @@ export const digitalTwinSettingsSchema = z.object({
});
export const soulSettingsSchema = digitalTwinSettingsSchema; // Alias for backwards compatibility
+// --- Phase 1: Quantitative Personality Modeling Schemas ---
+
+// Big Five personality traits (OCEAN model)
+export const bigFiveSchema = z.object({
+ O: z.number().min(0).max(1).describe('Openness to experience'),
+ C: z.number().min(0).max(1).describe('Conscientiousness'),
+ E: z.number().min(0).max(1).describe('Extraversion'),
+ A: z.number().min(0).max(1).describe('Agreeableness'),
+ N: z.number().min(0).max(1).describe('Neuroticism')
+});
+
+// Communication profile schema
+export const communicationProfileSchema = z.object({
+ formality: z.number().int().min(1).max(10).describe('1=very casual, 10=very formal'),
+ verbosity: z.number().int().min(1).max(10).describe('1=terse, 10=elaborate'),
+ avgSentenceLength: z.number().min(5).max(50).optional(),
+ emojiUsage: z.enum(['never', 'rare', 'occasional', 'frequent']).default('rare'),
+ preferredTone: z.string().max(100).optional(),
+ distinctiveMarkers: z.array(z.string().max(200)).max(10).optional()
+});
+
+// Valued trait with priority
+export const valuedTraitSchema = z.object({
+ value: z.string().min(1).max(100),
+ priority: z.number().int().min(1).max(10),
+ description: z.string().max(500).optional(),
+ conflictsWith: z.array(z.string()).optional()
+});
+
+// Full traits schema
+export const traitsSchema = z.object({
+ bigFive: bigFiveSchema.optional(),
+ valuesHierarchy: z.array(valuedTraitSchema).max(20).optional(),
+ communicationProfile: communicationProfileSchema.optional(),
+ lastAnalyzed: z.string().datetime().optional(),
+ analysisVersion: z.string().optional()
+});
+
+// --- Phase 2: Confidence Scoring Schemas ---
+
+// Confidence dimension enum
+export const confidenceDimensionEnum = z.enum([
+ 'openness', 'conscientiousness', 'extraversion', 'agreeableness', 'neuroticism',
+ 'values', 'communication', 'decision_making', 'boundaries', 'identity'
+]);
+
+// Gap recommendation
+export const gapRecommendationSchema = z.object({
+ dimension: confidenceDimensionEnum,
+ confidence: z.number().min(0).max(1),
+ evidenceCount: z.number().int().min(0),
+ requiredEvidence: z.number().int().min(1),
+ suggestedQuestions: z.array(z.string().max(500)).max(5),
+ suggestedCategory: enrichmentCategoryEnum.optional()
+});
+
+// Full confidence schema
+export const confidenceSchema = z.object({
+ overall: z.number().min(0).max(1),
+ dimensions: z.record(confidenceDimensionEnum, z.number().min(0).max(1)),
+ gaps: z.array(gapRecommendationSchema),
+ lastCalculated: z.string().datetime().optional()
+});
+
// Full meta.json schema
export const digitalTwinMetaSchema = z.object({
version: z.string().default('1.0.0'),
documents: z.array(documentMetaSchema).default([]),
testHistory: z.array(testHistoryEntrySchema).default([]),
enrichment: enrichmentProgressSchema.default({ completedCategories: [], lastSession: null }),
- settings: digitalTwinSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000 })
+ settings: digitalTwinSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000 }),
+ traits: traitsSchema.optional(),
+ confidence: confidenceSchema.optional()
});
export const soulMetaSchema = digitalTwinMetaSchema; // Alias for backwards compatibility
@@ -211,3 +277,25 @@ export const saveListDocumentInputSchema = z.object({
export const getListItemsInputSchema = z.object({
category: enrichmentCategoryEnum
});
+
+// --- Input schemas for trait and confidence endpoints ---
+
+// Analyze traits input
+export const analyzeTraitsInputSchema = z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1),
+ forceReanalyze: z.boolean().optional().default(false)
+});
+
+// Update traits input (manual override)
+export const updateTraitsInputSchema = z.object({
+ bigFive: bigFiveSchema.partial().optional(),
+ valuesHierarchy: z.array(valuedTraitSchema).max(20).optional(),
+ communicationProfile: communicationProfileSchema.partial().optional()
+});
+
+// Calculate confidence input
+export const calculateConfidenceInputSchema = z.object({
+ providerId: z.string().min(1).optional(),
+ model: z.string().min(1).optional()
+});
diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.js
index bb3b61c902..0e104e2017 100644
--- a/server/routes/digital-twin.js
+++ b/server/routes/digital-twin.js
@@ -28,7 +28,10 @@ import {
writingAnalysisInputSchema,
analyzeListInputSchema,
saveListDocumentInputSchema,
- getListItemsInputSchema
+ getListItemsInputSchema,
+ analyzeTraitsInputSchema,
+ updateTraitsInputSchema,
+ calculateConfidenceInputSchema
} from '../lib/digitalTwinValidation.js';
const router = Router();
@@ -458,4 +461,91 @@ router.post('/analyze-writing', asyncHandler(async (req, res) => {
res.json(result);
}));
+// =============================================================================
+// TRAITS & CONFIDENCE (Phase 1 & 2)
+// =============================================================================
+
+/**
+ * GET /api/digital-twin/traits
+ * Get current personality traits
+ */
+router.get('/traits', asyncHandler(async (req, res) => {
+ const traits = await digitalTwinService.getTraits();
+ res.json({ traits });
+}));
+
+/**
+ * POST /api/digital-twin/traits/analyze
+ * Analyze documents to extract personality traits using AI
+ */
+router.post('/traits/analyze', asyncHandler(async (req, res) => {
+ const validation = validate(analyzeTraitsInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { providerId, model, forceReanalyze } = validation.data;
+ const result = await digitalTwinService.analyzeTraits(providerId, model, forceReanalyze);
+ res.json(result);
+}));
+
+/**
+ * PUT /api/digital-twin/traits
+ * Manually update personality traits
+ */
+router.put('/traits', asyncHandler(async (req, res) => {
+ const validation = validate(updateTraitsInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const traits = await digitalTwinService.updateTraits(validation.data);
+ res.json({ traits });
+}));
+
+/**
+ * GET /api/digital-twin/confidence
+ * Get current confidence scores
+ */
+router.get('/confidence', asyncHandler(async (req, res) => {
+ const confidence = await digitalTwinService.getConfidence();
+ res.json({ confidence });
+}));
+
+/**
+ * POST /api/digital-twin/confidence/calculate
+ * Calculate confidence scores (optionally with AI analysis)
+ */
+router.post('/confidence/calculate', asyncHandler(async (req, res) => {
+ const validation = validate(calculateConfidenceInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { providerId, model } = validation.data;
+ const result = await digitalTwinService.calculateConfidence(providerId, model);
+ res.json(result);
+}));
+
+/**
+ * GET /api/digital-twin/gaps
+ * Get gap recommendations for personality enrichment
+ */
+router.get('/gaps', asyncHandler(async (req, res) => {
+ const gaps = await digitalTwinService.getGapRecommendations();
+ res.json({ gaps });
+}));
+
export default router;
diff --git a/server/services/digital-twin.js b/server/services/digital-twin.js
index ee44b88cf2..af610cfd4b 100644
--- a/server/services/digital-twin.js
+++ b/server/services/digital-twin.js
@@ -1692,3 +1692,438 @@ function parseWritingAnalysis(response) {
suggestedContent
};
}
+
+// =============================================================================
+// TRAIT ANALYSIS & CONFIDENCE SCORING (Phase 1 & 2)
+// =============================================================================
+
+/**
+ * Get all twin content for analysis (excludes behavioral tests)
+ */
+async function getAllTwinContent() {
+ const meta = await loadMeta();
+ const enabledDocs = meta.documents.filter(d => d.enabled && d.category !== 'behavioral');
+
+ const contents = [];
+ for (const doc of enabledDocs) {
+ const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
+ if (existsSync(filePath)) {
+ const content = await readFile(filePath, 'utf-8');
+ contents.push(`## ${doc.title} (${doc.filename})\n\n${content}`);
+ }
+ }
+
+ return contents.join('\n\n---\n\n');
+}
+
+/**
+ * Get current traits from meta
+ */
+export async function getTraits() {
+ const meta = await loadMeta();
+ return meta.traits || null;
+}
+
+/**
+ * Update traits manually (partial update)
+ */
+export async function updateTraits(updates) {
+ const meta = await loadMeta();
+ const currentTraits = meta.traits || {};
+
+ const newTraits = {
+ ...currentTraits,
+ lastAnalyzed: new Date().toISOString(),
+ analysisVersion: 'manual'
+ };
+
+ // Merge Big Five if provided
+ if (updates.bigFive) {
+ newTraits.bigFive = { ...currentTraits.bigFive, ...updates.bigFive };
+ }
+
+ // Replace values hierarchy if provided
+ if (updates.valuesHierarchy) {
+ newTraits.valuesHierarchy = updates.valuesHierarchy;
+ }
+
+ // Merge communication profile if provided
+ if (updates.communicationProfile) {
+ newTraits.communicationProfile = {
+ ...currentTraits.communicationProfile,
+ ...updates.communicationProfile
+ };
+ }
+
+ meta.traits = newTraits;
+ await saveMeta(meta);
+ digitalTwinEvents.emit('traits:updated', newTraits);
+
+ return newTraits;
+}
+
+/**
+ * Analyze digital twin documents to extract personality traits
+ */
+export async function analyzeTraits(providerId, model, forceReanalyze = false) {
+ const meta = await loadMeta();
+
+ // Check if we have recent analysis and don't need to reanalyze
+ if (!forceReanalyze && meta.traits?.lastAnalyzed) {
+ const lastAnalyzed = new Date(meta.traits.lastAnalyzed);
+ const hoursSince = (Date.now() - lastAnalyzed.getTime()) / (1000 * 60 * 60);
+ if (hoursSince < 24) {
+ return { traits: meta.traits, cached: true };
+ }
+ }
+
+ const twinContent = await getAllTwinContent();
+ if (!twinContent || twinContent.length < 100) {
+ return { error: 'Not enough digital twin content to analyze. Add more documents first.' };
+ }
+
+ const prompt = await buildPrompt('twin-trait-extractor', {
+ twinContent
+ }).catch(() => null);
+
+ if (!prompt) {
+ return { error: 'Trait extractor prompt template not found' };
+ }
+
+ const provider = await getProviderById(providerId);
+ if (!provider || !provider.enabled) {
+ return { error: 'Provider not found or disabled' };
+ }
+
+ if (provider.type === 'api') {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) {
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ }
+
+ const response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.3,
+ max_tokens: 3000
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ const responseText = data.choices?.[0]?.message?.content || '';
+ const parsedTraits = parseTraitsResponse(responseText);
+
+ if (parsedTraits.error) {
+ return parsedTraits;
+ }
+
+ // Save to meta
+ const traits = {
+ bigFive: parsedTraits.bigFive,
+ valuesHierarchy: parsedTraits.valuesHierarchy,
+ communicationProfile: parsedTraits.communicationProfile,
+ lastAnalyzed: new Date().toISOString(),
+ analysisVersion: '1.0'
+ };
+
+ meta.traits = traits;
+ await saveMeta(meta);
+ digitalTwinEvents.emit('traits:analyzed', traits);
+
+ return { traits, analysisNotes: parsedTraits.analysisNotes };
+ }
+
+ return { error: `Provider request failed: ${response.status}` };
+ }
+
+ return { error: 'Provider type not supported for trait analysis' };
+}
+
+function parseTraitsResponse(response) {
+ const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
+ if (jsonMatch) {
+ const parsed = JSON.parse(jsonMatch[1]);
+ return parsed;
+ }
+
+ if (response.trim().startsWith('{')) {
+ return JSON.parse(response);
+ }
+
+ return { error: 'Failed to parse traits response', rawResponse: response };
+}
+
+/**
+ * Get current confidence scores from meta
+ */
+export async function getConfidence() {
+ const meta = await loadMeta();
+ return meta.confidence || null;
+}
+
+/**
+ * Calculate confidence scores for all personality dimensions
+ */
+export async function calculateConfidence(providerId, model) {
+ const twinContent = await getAllTwinContent();
+ const meta = await loadMeta();
+ const currentTraits = meta.traits || {};
+
+ // If no provider specified, do local calculation
+ if (!providerId || !model) {
+ return calculateLocalConfidence(twinContent, currentTraits, meta);
+ }
+
+ const prompt = await buildPrompt('twin-confidence-analyzer', {
+ twinContent,
+ currentTraits: JSON.stringify(currentTraits, null, 2)
+ }).catch(() => null);
+
+ if (!prompt) {
+ // Fall back to local calculation
+ return calculateLocalConfidence(twinContent, currentTraits, meta);
+ }
+
+ const provider = await getProviderById(providerId);
+ if (!provider || !provider.enabled) {
+ return calculateLocalConfidence(twinContent, currentTraits, meta);
+ }
+
+ if (provider.type === 'api') {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) {
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ }
+
+ const response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.3,
+ max_tokens: 2000
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ const responseText = data.choices?.[0]?.message?.content || '';
+ const parsed = parseConfidenceResponse(responseText);
+
+ if (!parsed.error) {
+ const confidence = {
+ ...parsed,
+ lastCalculated: new Date().toISOString()
+ };
+
+ meta.confidence = confidence;
+ await saveMeta(meta);
+ digitalTwinEvents.emit('confidence:calculated', confidence);
+
+ return { confidence };
+ }
+ }
+ }
+
+ // Fall back to local calculation
+ return calculateLocalConfidence(twinContent, currentTraits, meta);
+}
+
+function parseConfidenceResponse(response) {
+ const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
+ if (jsonMatch) {
+ return JSON.parse(jsonMatch[1]);
+ }
+
+ if (response.trim().startsWith('{')) {
+ return JSON.parse(response);
+ }
+
+ return { error: 'Failed to parse confidence response' };
+}
+
+/**
+ * Calculate confidence locally without LLM (simpler heuristic-based)
+ */
+async function calculateLocalConfidence(twinContent, traits, meta) {
+ const contentLower = twinContent.toLowerCase();
+ const documents = await getDocuments();
+ const enabledDocs = documents.filter(d => d.enabled && d.category !== 'behavioral');
+
+ // Evidence counts based on keyword presence and document existence
+ const dimensions = {
+ openness: calculateDimensionConfidence(contentLower, ['curious', 'creative', 'explore', 'novel', 'experiment', 'learn'], traits?.bigFive?.O),
+ conscientiousness: calculateDimensionConfidence(contentLower, ['organize', 'plan', 'discipline', 'routine', 'structure', 'systematic'], traits?.bigFive?.C),
+ extraversion: calculateDimensionConfidence(contentLower, ['social', 'energy', 'people', 'outgoing', 'network', 'collaborate'], traits?.bigFive?.E),
+ agreeableness: calculateDimensionConfidence(contentLower, ['empathy', 'cooperate', 'trust', 'kind', 'help', 'support'], traits?.bigFive?.A),
+ neuroticism: calculateDimensionConfidence(contentLower, ['stress', 'anxiety', 'emotion', 'worry', 'calm', 'stable'], traits?.bigFive?.N),
+ values: calculateDimensionConfidence(contentLower, ['value', 'principle', 'believe', 'important', 'priority', 'matter'], null, enabledDocs.some(d => d.filename.toLowerCase().includes('value'))),
+ communication: calculateDimensionConfidence(contentLower, ['communicate', 'prefer', 'feedback', 'tone', 'style', 'write'], null, enabledDocs.some(d => d.filename.toLowerCase().includes('communi') || d.filename.toLowerCase().includes('writing'))),
+ decision_making: calculateDimensionConfidence(contentLower, ['decision', 'choose', 'heuristic', 'rule', 'approach', 'consider'], null, enabledDocs.some(d => d.filename.toLowerCase().includes('decision'))),
+ boundaries: calculateDimensionConfidence(contentLower, ['never', 'boundary', 'non-negotiable', 'refuse', 'limit', 'error'], null, enabledDocs.some(d => d.filename.toLowerCase().includes('non_negot') || d.filename.toLowerCase().includes('error'))),
+ identity: calculateDimensionConfidence(contentLower, ['name', 'who i am', 'identity', 'role', 'purpose', 'mission'], null, enabledDocs.some(d => d.filename.toLowerCase().includes('soul') || d.category === 'core'))
+ };
+
+ // Calculate overall
+ const scores = Object.values(dimensions);
+ const overall = scores.reduce((a, b) => a + b, 0) / scores.length;
+
+ // Generate gaps for low-confidence dimensions
+ const gaps = generateGapRecommendations(dimensions);
+
+ const confidence = {
+ overall: Math.round(overall * 100) / 100,
+ dimensions,
+ gaps,
+ lastCalculated: new Date().toISOString()
+ };
+
+ meta.confidence = confidence;
+ await saveMeta(meta);
+ digitalTwinEvents.emit('confidence:calculated', confidence);
+
+ return { confidence, method: 'local' };
+}
+
+function calculateDimensionConfidence(content, keywords, existingScore, hasDocument = false) {
+ let score = 0;
+
+ // Keyword evidence (up to 0.5)
+ const keywordHits = keywords.filter(k => content.includes(k)).length;
+ score += Math.min(0.5, keywordHits * 0.1);
+
+ // Document existence bonus (0.2)
+ if (hasDocument) score += 0.2;
+
+ // Existing trait score bonus (0.3)
+ if (existingScore !== undefined && existingScore !== null) score += 0.3;
+
+ return Math.min(1, Math.round(score * 100) / 100);
+}
+
+function generateGapRecommendations(dimensions) {
+ const gaps = [];
+ const threshold = 0.6;
+
+ const dimensionConfig = {
+ openness: {
+ suggestedCategory: 'personality_assessments',
+ questions: [
+ 'How do you typically react to new ideas or unconventional approaches?',
+ 'What topics or subjects consistently spark your curiosity?',
+ 'How comfortable are you with ambiguity and uncertainty?'
+ ]
+ },
+ conscientiousness: {
+ suggestedCategory: 'daily_routines',
+ questions: [
+ 'Describe your typical approach to planning and organization.',
+ 'How do you handle deadlines and commitments?',
+ 'What systems or routines keep you productive?'
+ ]
+ },
+ extraversion: {
+ suggestedCategory: 'communication',
+ questions: [
+ 'How do you prefer to spend your free time - with others or alone?',
+ 'In group settings, do you tend to lead conversations or observe?',
+ 'Where do you get your energy from - social interaction or solitude?'
+ ]
+ },
+ agreeableness: {
+ suggestedCategory: 'values',
+ questions: [
+ 'How do you typically handle disagreements with others?',
+ 'What role does empathy play in your decision-making?',
+ 'How do you balance your needs with the needs of others?'
+ ]
+ },
+ neuroticism: {
+ suggestedCategory: 'personality_assessments',
+ questions: [
+ 'How do you typically respond to unexpected setbacks or failures?',
+ 'What situations tend to make you feel anxious or stressed?',
+ 'How would others describe your emotional stability?'
+ ]
+ },
+ values: {
+ suggestedCategory: 'values',
+ questions: [
+ 'What principles guide your most important decisions?',
+ 'Which values would you never compromise, even under pressure?',
+ 'What do you want to be known for?'
+ ]
+ },
+ communication: {
+ suggestedCategory: 'communication',
+ questions: [
+ 'How do you prefer to receive feedback - direct or diplomatic?',
+ 'What communication styles do you find most effective?',
+ 'How would you describe your writing voice?'
+ ]
+ },
+ decision_making: {
+ suggestedCategory: 'decision_heuristics',
+ questions: [
+ 'What mental shortcuts or rules of thumb guide your choices?',
+ 'How do you balance intuition vs. analysis in decisions?',
+ 'What factors do you prioritize when making important choices?'
+ ]
+ },
+ boundaries: {
+ suggestedCategory: 'non_negotiables',
+ questions: [
+ 'What behaviors or requests would you always refuse?',
+ 'What principles are absolutely non-negotiable for you?',
+ 'What should your digital twin never do or say?'
+ ]
+ },
+ identity: {
+ suggestedCategory: 'core_memories',
+ questions: [
+ 'How would you introduce yourself in one sentence?',
+ 'What makes you uniquely you?',
+ 'What is your core purpose or mission?'
+ ]
+ }
+ };
+
+ for (const [dimension, score] of Object.entries(dimensions)) {
+ if (score < threshold) {
+ const config = dimensionConfig[dimension];
+ gaps.push({
+ dimension,
+ confidence: score,
+ evidenceCount: Math.round(score * 5),
+ requiredEvidence: 5,
+ suggestedQuestions: config?.questions || [],
+ suggestedCategory: config?.suggestedCategory || 'core_memories'
+ });
+ }
+ }
+
+ // Sort by confidence (lowest first)
+ gaps.sort((a, b) => a.confidence - b.confidence);
+
+ return gaps;
+}
+
+/**
+ * Get gap recommendations (prioritized list of what to enrich)
+ */
+export async function getGapRecommendations() {
+ const meta = await loadMeta();
+
+ // If no confidence data, calculate it first
+ if (!meta.confidence) {
+ const result = await calculateConfidence();
+ return result.confidence?.gaps || [];
+ }
+
+ return meta.confidence.gaps || [];
+}