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: enhance Soul with completeness validation, contradiction detection, dynamic tests

Adam Eivy2908502f4be5
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.md
index efef1fe7f9..816541dba5 100644
--- a/.changelog/v0.10.x.md
+++ b/.changelog/v0.10.x.md
@@ -40,6 +40,25 @@ This release introduces a structured changelog documentation system for creating
- **Prompt Templates**: `/api/prompts` endpoints for managing reusable prompt templates
- **Automatic Symlink**: Template creates symlinks to PortOS's ai-toolkit package for shared functionality
+### Soul - Digital Twin Identity System
+- **Soul Documents**: New `/soul` page for managing identity scaffold documents that define persona, values, and cognitive style
+- **Document Management**: View, edit, create, and delete soul markdown documents organized by category (core, audio, behavioral, enrichment)
+- **Multi-Model Behavioral Testing**: Run 14 behavioral alignment tests against multiple AI providers/models simultaneously with side-by-side comparison
+- **Enrichment System**: Guided questionnaire across 13 categories (memories, favorites, values, routines, non-negotiables, decision heuristics, error intolerance, etc.) that generates soul document content from answers
+- **Export Formats**: Export soul for use in external LLMs as System Prompt, CLAUDE.md, JSON, or individual files
+- **CoS Integration**: Soul context automatically injected into Chief of Staff agent prompts when enabled
+- **Identity Navigation Group**: Brain and Soul now grouped under "Identity" section in navigation
+
+### Soul Enhancement: Reliable Digital Twins
+- **Completeness Validator**: New API endpoint and UI showing percentage of required identity sections covered (identity, values, communication, decision making, non-negotiables, error intolerance) with actionable suggestions for missing sections
+- **Contradiction Detector**: AI-powered analysis to detect inconsistencies and conflicting statements across soul documents with severity levels and resolution suggestions
+- **Dynamic Test Generation**: Generate behavioral tests automatically based on soul content - tests values in action, communication style, non-negotiables, and decision patterns
+- **Writing Sample Analysis**: Paste writing samples to extract your authentic voice patterns (sentence structure, vocabulary, formality, tone) and automatically generate a WRITING_STYLE.md document
+- **Soul Creation Wizard**: 5-step guided wizard for new users covering identity basics, core values, communication style, decision making, and non-negotiables
+- **Document Weighting**: Priority slider (1-10) on each document - higher weighted documents are preserved first when context limits force truncation
+- **New Enrichment Categories**: Added non_negotiables, decision_heuristics, and error_intolerance categories with 3 preset questions each
+- **Best Practices Documentation**: Added SOUL_GUIDE.md with comprehensive guidance on creating effective soul documents
+
## 🔧 Improvements
### Release Process
diff --git a/PLAN.md b/PLAN.md
index 61001a42dd..77b3cd3137 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -55,6 +55,7 @@ pm2 logs
- [x] M30: Configurable Intervals - Per-task-type scheduling (daily, weekly, once, on-demand)
- [x] M31: LLM Memory Classification - Intelligent memory extraction with quality filtering
- [x] M32: Brain System - Second-brain capture and classification. See [Brain System](./docs/features/brain-system.md)
+- [x] M33: Soul System - Digital twin identity scaffold management
### Documentation
- [Architecture Overview](./docs/ARCHITECTURE.md) - System design, data flow
@@ -73,6 +74,7 @@ pm2 logs
- [Error Handling](./docs/features/error-handling.md) - Graceful error handling with auto-fix
- [Memory System](./docs/features/memory-system.md) - Semantic memory with LLM classification
- [Brain System](./docs/features/brain-system.md) - Second-brain capture and classification
+- [Soul System](#m33-soul-system) - Digital twin identity scaffold management
### Error Handling
The server implements comprehensive error handling:
@@ -511,3 +513,104 @@ Enhancements to the Chief of Staff system for better task learning, smarter prio
2. **Enhanced Performance Tracking** - `getPerformanceSummary()` function provides overall success rate, top performers, tasks needing attention
3. **Learning Insights System** - `recordLearningInsight()` and `getRecentInsights()` for storing and retrieving observations
4. **Periodic Performance Logging** - Every 10 evaluations, CoS logs success rate and task performance stats
+
+---
+
+### M33: Soul System
+
+Digital twin identity scaffold management for creating and testing aligned AI personas.
+
+#### Problem
+LLMs can embody specific personas, but creating comprehensive identity documents and testing alignment across different models is manual and error-prone.
+
+#### Solution
+A dedicated Soul page (`/soul`) with five tabs:
+
+1. **Overview Tab**: Dashboard showing soul health score, document counts, test scores, enrichment progress, and quick actions
+2. **Documents Tab**: Sidebar-based document editor for managing soul markdown files by category (core, audio, behavioral, enrichment)
+3. **Test Tab**: Multi-model behavioral testing against 14 predefined tests, with side-by-side result comparison
+4. **Enrich Tab**: Guided questionnaire across 10 categories that generates soul document content from answers
+5. **Export Tab**: Export soul for use in external LLMs (System Prompt, CLAUDE.md, JSON, individual files)
+
+#### Directory Structure
+```
+data/soul/
+├── meta.json # Document metadata, test history, settings
+├── SOUL.md # Core identity
+├── Expanded.md # High-fidelity spec
+├── BEHAVIORAL_TEST_SUITE.md # 14 behavioral tests
+├── AUDIO*.md # Audio preferences
+├── MEMORIES.md # Generated via enrichment
+├── FAVORITES.md # Generated via enrichment
+└── PREFERENCES.md # Generated via enrichment
+```
+
+#### CoS Integration
+- Soul context automatically injected into agent prompts when enabled
+- Settings control `autoInjectToCoS` and `maxContextTokens`
+- Prompt template `cos-agent-briefing.md` includes `{{soulSection}}`
+
+#### Enrichment Categories
+| Category | Description |
+|----------|-------------|
+| Core Memories | Formative experiences |
+| Favorite Books | Books that shaped thinking |
+| Favorite Movies | Films that resonate |
+| Music Taste | Cognitive infrastructure |
+| Communication | How to give/receive info |
+| Decision Making | Approach to choices |
+| Values | Core principles |
+| Aesthetics | Visual preferences |
+| Daily Routines | Structure habits |
+| Career/Skills | Professional expertise |
+
+#### API Endpoints
+| Route | Description |
+|-------|-------------|
+| GET /api/soul | Status summary |
+| GET /api/soul/documents | List documents |
+| POST /api/soul/documents | Create document |
+| PUT /api/soul/documents/:id | Update document |
+| DELETE /api/soul/documents/:id | Delete document |
+| GET /api/soul/tests | Get test suite |
+| POST /api/soul/tests/run | Run single-model tests |
+| POST /api/soul/tests/run-multi | Run multi-model tests |
+| GET /api/soul/enrich/categories | List enrichment categories |
+| POST /api/soul/enrich/question | Get next question |
+| POST /api/soul/enrich/answer | Submit answer |
+| POST /api/soul/export | Export soul |
+| GET /api/soul/validate/completeness | Check soul completeness |
+| POST /api/soul/validate/contradictions | Detect contradictions |
+| POST /api/soul/tests/generate | Generate dynamic tests |
+| POST /api/soul/analyze-writing | Analyze writing samples |
+
+#### Soul Enhancement: Reliable Digital Twins (M33.1)
+
+Additional features to create more reliable digital twins through improved data collection, validation, testing, and user guidance.
+
+##### New Enrichment Categories
+Added 3 new categories with 3 preset questions each:
+- **non_negotiables**: Principles and boundaries that define your limits
+- **decision_heuristics**: Mental models and shortcuts for making choices
+- **error_intolerance**: What your digital twin should never do
+
+##### Validation & Analysis
+1. **Completeness Validator**: Checks for 6 required sections (identity, values, communication, decision making, non-negotiables, error intolerance), shows percentage complete with actionable suggestions
+2. **Contradiction Detector**: AI-powered analysis to find inconsistencies between soul documents, with severity levels and resolution suggestions
+
+##### Dynamic Testing
+- **Generate Tests**: AI generates behavioral tests based on soul content, targeting values, communication style, non-negotiables, and decision patterns
+- Returns structured tests with prompts, expected behaviors, and failure signals
+
+##### Writing Sample Analysis
+- Paste writing samples to extract authentic voice patterns
+- Analyzes: sentence structure, vocabulary, formality, tone, distinctive markers
+- Generates WRITING_STYLE.md document content
+
+##### User Guidance
+1. **Soul Creation Wizard**: 5-step guided wizard for new users (identity, values, communication, decisions, boundaries)
+2. **Best Practices Documentation**: SOUL_GUIDE.md with comprehensive guidance on creating effective soul documents
+
+##### Context Optimization
+- **Document Weighting**: Priority slider (1-10) on each document
+- Higher weighted documents preserved first when context limits force truncation
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 97eb919c99..f1645f23ed 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -9,6 +9,7 @@ import PromptManager from './pages/PromptManager';
import ChiefOfStaff from './pages/ChiefOfStaff';
import Brain from './pages/Brain';
import Media from './pages/Media';
+import Soul from './pages/Soul';
// Lazy load heavier pages for code splitting
// DevTools pages are large (~2300 lines total) so lazy load them
@@ -49,6 +50,8 @@ export default function App() {
<Route path="cos/:tab" element={<ChiefOfStaff />} />
<Route path="brain" element={<Navigate to="/brain/inbox" replace />} />
<Route path="brain/:tab" element={<Brain />} />
+ <Route path="soul" element={<Navigate to="/soul/overview" replace />} />
+ <Route path="soul/:tab" element={<Soul />} />
<Route path="apps/create" element={<CreateApp />} />
<Route path="templates" element={<Templates />} />
<Route path="media" element={<Media />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 6a2ec180af..c836b244f4 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -21,7 +21,9 @@ import {
Crown,
Play,
Camera,
- Brain
+ Brain,
+ Heart,
+ Fingerprint
} from 'lucide-react';
import packageJson from '../../package.json';
import Logo from './Logo';
@@ -42,8 +44,15 @@ const navItems = [
},
{ to: '/apps', label: 'Apps', icon: Package, single: true },
{ href: '//:5560', label: 'Autofixer', icon: Wrench, external: true, dynamicHost: true },
- { to: '/brain', label: 'Brain', icon: Brain, single: true },
{ to: '/cos', label: 'Chief of Staff', icon: Crown, single: true, showBadge: true },
+ {
+ label: 'Identity',
+ icon: Fingerprint,
+ children: [
+ { to: '/brain', label: 'Brain', icon: Brain },
+ { to: '/soul', label: 'Soul', icon: Heart }
+ ]
+ },
{
label: 'Dev Tools',
icon: Terminal,
@@ -395,8 +404,8 @@ export default function Layout() {
</header>
{/* Main content */}
- <main id="main-content" className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') ? '' : 'p-4 md:p-6'}`}>
- {location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') ? (
+ <main id="main-content" className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/soul') ? '' : 'p-4 md:p-6'}`}>
+ {location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/soul') ? (
<Outlet />
) : (
<div className="max-w-7xl mx-auto">
diff --git a/client/src/components/soul/SoulWizard.jsx b/client/src/components/soul/SoulWizard.jsx
new file mode 100644
index 0000000000..b44def8312
--- /dev/null
+++ b/client/src/components/soul/SoulWizard.jsx
@@ -0,0 +1,272 @@
+import { useState } from 'react';
+import {
+ ChevronRight,
+ ChevronLeft,
+ User,
+ Heart,
+ MessageSquare,
+ GitBranch,
+ Shield,
+ Check,
+ RefreshCw,
+ Sparkles
+} from 'lucide-react';
+import * as api from '../../services/api';
+import toast from 'react-hot-toast';
+
+const WIZARD_STEPS = [
+ {
+ id: 'identity',
+ title: 'Identity Basics',
+ description: 'Who are you?',
+ icon: User,
+ fields: [
+ { id: 'name', label: 'Name', placeholder: 'Your name', type: 'text' },
+ { id: 'role', label: 'Primary Role', placeholder: 'e.g., Software Engineer, Designer, Writer', type: 'text' },
+ { id: 'oneLiner', label: 'One-liner', placeholder: 'Describe yourself in one sentence', type: 'text' }
+ ]
+ },
+ {
+ id: 'values',
+ title: 'Core Values',
+ description: 'What matters most to you?',
+ icon: Heart,
+ fields: [
+ { id: 'value1', label: 'Value 1', placeholder: 'e.g., Intellectual honesty', type: 'text' },
+ { id: 'value2', label: 'Value 2', placeholder: 'e.g., Continuous learning', type: 'text' },
+ { id: 'value3', label: 'Value 3', placeholder: 'e.g., Craftsmanship', type: 'text' }
+ ]
+ },
+ {
+ id: 'communication',
+ title: 'Communication Style',
+ description: 'How do you communicate?',
+ icon: MessageSquare,
+ fields: [
+ { id: 'tone', label: 'Preferred Tone', placeholder: 'e.g., Direct but warm, formal, casual', type: 'text' },
+ { id: 'feedback', label: 'Feedback Preference', placeholder: 'How do you like to receive feedback?', type: 'text' },
+ { id: 'verbosity', label: 'Verbosity', placeholder: 'e.g., Concise, detailed, depends on context', type: 'text' }
+ ]
+ },
+ {
+ id: 'decisions',
+ title: 'Decision Making',
+ description: 'How do you make choices?',
+ icon: GitBranch,
+ fields: [
+ { id: 'speed', label: 'Decision Speed', placeholder: 'Quick decider or deliberate thinker?', type: 'text' },
+ { id: 'approach', label: 'Approach', placeholder: 'e.g., Data-driven, intuition-guided, balanced', type: 'text' },
+ { id: 'risk', label: 'Risk Tolerance', placeholder: 'How comfortable are you with uncertainty?', type: 'text' }
+ ]
+ },
+ {
+ id: 'boundaries',
+ title: 'Non-Negotiables',
+ description: 'What should your twin never do?',
+ icon: Shield,
+ fields: [
+ { id: 'boundary1', label: 'Boundary 1', placeholder: 'What behavior is unacceptable?', type: 'text' },
+ { id: 'boundary2', label: 'Boundary 2', placeholder: 'What topic should be avoided?', type: 'text' },
+ { id: 'irritant', label: 'Pet Peeve', placeholder: 'What communication style irritates you?', type: 'text' }
+ ]
+ }
+];
+
+export default function SoulWizard({ onComplete, onCancel }) {
+ const [currentStep, setCurrentStep] = useState(0);
+ const [formData, setFormData] = useState({});
+ const [saving, setSaving] = useState(false);
+
+ const step = WIZARD_STEPS[currentStep];
+ const StepIcon = step.icon;
+ const isLastStep = currentStep === WIZARD_STEPS.length - 1;
+ const progress = ((currentStep + 1) / WIZARD_STEPS.length) * 100;
+
+ const updateField = (fieldId, value) => {
+ setFormData({
+ ...formData,
+ [step.id]: {
+ ...(formData[step.id] || {}),
+ [fieldId]: value
+ }
+ });
+ };
+
+ const canProceed = () => {
+ const stepData = formData[step.id] || {};
+ return step.fields.some(f => stepData[f.id]?.trim());
+ };
+
+ const generateSoulDocument = () => {
+ const { identity = {}, values = {}, communication = {}, decisions = {}, boundaries = {} } = formData;
+
+ return `# Soul Document
+
+## Identity
+
+**Name**: ${identity.name || 'Not specified'}
+**Role**: ${identity.role || 'Not specified'}
+**One-liner**: ${identity.oneLiner || 'Not specified'}
+
+## Core Values
+
+${values.value1 ? `1. **${values.value1}**` : ''}
+${values.value2 ? `2. **${values.value2}**` : ''}
+${values.value3 ? `3. **${values.value3}**` : ''}
+
+## Communication Style
+
+- **Preferred Tone**: ${communication.tone || 'Not specified'}
+- **Feedback Preference**: ${communication.feedback || 'Not specified'}
+- **Verbosity**: ${communication.verbosity || 'Not specified'}
+
+## Decision Making
+
+- **Decision Speed**: ${decisions.speed || 'Not specified'}
+- **Approach**: ${decisions.approach || 'Not specified'}
+- **Risk Tolerance**: ${decisions.risk || 'Not specified'}
+
+## Non-Negotiables
+
+${boundaries.boundary1 ? `- **Boundary**: ${boundaries.boundary1}` : ''}
+${boundaries.boundary2 ? `- **Avoid**: ${boundaries.boundary2}` : ''}
+${boundaries.irritant ? `- **Pet Peeve**: ${boundaries.irritant}` : ''}
+
+---
+*Generated via Soul Creation Wizard*
+`.trim();
+ };
+
+ const handleComplete = async () => {
+ setSaving(true);
+ const content = generateSoulDocument();
+
+ await api.createSoulDocument({
+ filename: 'SOUL.md',
+ title: 'Soul',
+ category: 'core',
+ content
+ });
+
+ toast.success('Soul document created!');
+ setSaving(false);
+ onComplete();
+ };
+
+ return (
+ <div className="bg-port-card rounded-lg border border-port-accent/30 p-6">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-6">
+ <div className="flex items-center gap-3">
+ <Sparkles className="w-6 h-6 text-port-accent" />
+ <h2 className="text-xl font-bold text-white">Create Your Soul</h2>
+ </div>
+ <button
+ onClick={onCancel}
+ className="text-gray-400 hover:text-white"
+ >
+ Skip for now
+ </button>
+ </div>
+
+ {/* Progress Bar */}
+ <div className="mb-6">
+ <div className="flex items-center justify-between text-sm text-gray-400 mb-2">
+ <span>Step {currentStep + 1} of {WIZARD_STEPS.length}</span>
+ <span>{Math.round(progress)}% complete</span>
+ </div>
+ <div className="h-2 bg-port-border rounded-full overflow-hidden">
+ <div
+ className="h-full bg-port-accent transition-all"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ </div>
+
+ {/* Step Header */}
+ <div className="flex items-center gap-4 mb-6">
+ <div className="p-3 rounded-lg bg-port-accent/20">
+ <StepIcon className="w-6 h-6 text-port-accent" />
+ </div>
+ <div>
+ <h3 className="text-lg font-semibold text-white">{step.title}</h3>
+ <p className="text-gray-400">{step.description}</p>
+ </div>
+ </div>
+
+ {/* Fields */}
+ <div className="space-y-4 mb-6">
+ {step.fields.map(field => (
+ <div key={field.id}>
+ <label className="block text-sm text-gray-400 mb-1">{field.label}</label>
+ <input
+ type={field.type}
+ value={formData[step.id]?.[field.id] || ''}
+ onChange={(e) => updateField(field.id, e.target.value)}
+ placeholder={field.placeholder}
+ className="w-full px-4 py-2 bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ ))}
+ </div>
+
+ {/* Navigation */}
+ <div className="flex items-center justify-between">
+ <button
+ onClick={() => setCurrentStep(Math.max(0, currentStep - 1))}
+ disabled={currentStep === 0}
+ className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <ChevronLeft size={18} />
+ Back
+ </button>
+
+ {isLastStep ? (
+ <button
+ onClick={handleComplete}
+ disabled={saving || !canProceed()}
+ className="flex items-center gap-2 px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {saving ? (
+ <>
+ <RefreshCw className="w-4 h-4 animate-spin" />
+ Creating...
+ </>
+ ) : (
+ <>
+ <Check size={18} />
+ Create Soul
+ </>
+ )}
+ </button>
+ ) : (
+ <button
+ onClick={() => setCurrentStep(Math.min(WIZARD_STEPS.length - 1, currentStep + 1))}
+ disabled={!canProceed()}
+ className="flex items-center gap-2 px-6 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ Next
+ <ChevronRight size={18} />
+ </button>
+ )}
+ </div>
+
+ {/* Step Indicators */}
+ <div className="flex items-center justify-center gap-2 mt-6">
+ {WIZARD_STEPS.map((s, index) => (
+ <button
+ key={s.id}
+ onClick={() => setCurrentStep(index)}
+ className={`w-2 h-2 rounded-full transition-colors ${
+ index === currentStep
+ ? 'bg-port-accent'
+ : index < currentStep
+ ? 'bg-green-500'
+ : 'bg-port-border'
+ }`}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/soul/constants.js b/client/src/components/soul/constants.js
new file mode 100644
index 0000000000..d9b0f6782a
--- /dev/null
+++ b/client/src/components/soul/constants.js
@@ -0,0 +1,261 @@
+import {
+ Heart,
+ FileText,
+ CheckCircle,
+ Sparkles,
+ Download,
+ Settings,
+ BookOpen,
+ Film,
+ Music,
+ MessageSquare,
+ Brain,
+ Palette,
+ Clock,
+ Briefcase,
+ Star,
+ Tv,
+ Users,
+ Coffee,
+ Paintbrush,
+ Shield,
+ GitBranch,
+ AlertOctagon
+} from 'lucide-react';
+
+// Main navigation tabs
+export const TABS = [
+ { id: 'overview', label: 'Overview', icon: Heart },
+ { id: 'documents', label: 'Documents', icon: FileText },
+ { id: 'test', label: 'Test', icon: CheckCircle },
+ { id: 'enrich', label: 'Enrich', icon: Sparkles },
+ { id: 'export', label: 'Export', icon: Download }
+];
+
+// Document category configurations
+export const DOCUMENT_CATEGORIES = {
+ core: {
+ label: 'Core Identity',
+ color: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
+ icon: Heart
+ },
+ audio: {
+ label: 'Audio/Music',
+ color: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
+ icon: Music
+ },
+ behavioral: {
+ label: 'Behavioral Tests',
+ color: 'bg-green-500/20 text-green-400 border-green-500/30',
+ icon: CheckCircle
+ },
+ enrichment: {
+ label: 'Enrichment',
+ color: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
+ icon: Sparkles
+ },
+ entertainment: {
+ label: 'Entertainment',
+ color: 'bg-red-500/20 text-red-400 border-red-500/30',
+ icon: Tv
+ },
+ professional: {
+ label: 'Professional',
+ color: 'bg-indigo-500/20 text-indigo-400 border-indigo-500/30',
+ icon: Briefcase
+ },
+ lifestyle: {
+ label: 'Lifestyle',
+ color: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30',
+ icon: Coffee
+ },
+ social: {
+ label: 'Social',
+ color: 'bg-pink-500/20 text-pink-400 border-pink-500/30',
+ icon: Users
+ },
+ creative: {
+ label: 'Creative',
+ color: 'bg-orange-500/20 text-orange-400 border-orange-500/30',
+ icon: Paintbrush
+ }
+};
+
+// Test result status colors
+export const TEST_STATUS = {
+ passed: {
+ label: 'Passed',
+ color: 'bg-green-500/20 text-green-400 border-green-500/30'
+ },
+ partial: {
+ label: 'Partial',
+ color: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30'
+ },
+ failed: {
+ label: 'Failed',
+ color: 'bg-red-500/20 text-red-400 border-red-500/30'
+ },
+ pending: {
+ label: 'Pending',
+ color: 'bg-gray-500/20 text-gray-400 border-gray-500/30'
+ }
+};
+
+// Enrichment category configurations
+export const ENRICHMENT_CATEGORIES = {
+ core_memories: {
+ id: 'core_memories',
+ label: 'Core Memories',
+ description: 'Formative experiences that shaped your identity',
+ icon: Star,
+ color: 'purple'
+ },
+ favorite_books: {
+ id: 'favorite_books',
+ label: 'Favorite Books',
+ description: 'Books that shaped your thinking',
+ icon: BookOpen,
+ color: 'blue'
+ },
+ favorite_movies: {
+ id: 'favorite_movies',
+ label: 'Favorite Movies',
+ description: 'Films that resonate with your aesthetic and values',
+ icon: Film,
+ color: 'red'
+ },
+ music_taste: {
+ id: 'music_taste',
+ label: 'Music Taste',
+ description: 'Music as cognitive infrastructure',
+ icon: Music,
+ color: 'green'
+ },
+ communication: {
+ id: 'communication',
+ label: 'Communication Style',
+ description: 'How you prefer to give and receive information',
+ icon: MessageSquare,
+ color: 'cyan'
+ },
+ decision_making: {
+ id: 'decision_making',
+ label: 'Decision Making',
+ description: 'How you approach choices and uncertainty',
+ icon: Brain,
+ color: 'orange'
+ },
+ values: {
+ id: 'values',
+ label: 'Values',
+ description: 'Core principles that guide your actions',
+ icon: Heart,
+ color: 'pink'
+ },
+ aesthetics: {
+ id: 'aesthetics',
+ label: 'Aesthetic Preferences',
+ description: 'Visual and design sensibilities',
+ icon: Palette,
+ color: 'violet'
+ },
+ daily_routines: {
+ id: 'daily_routines',
+ label: 'Daily Routines',
+ description: 'Habits and rhythms that structure your day',
+ icon: Clock,
+ color: 'amber'
+ },
+ career_skills: {
+ id: 'career_skills',
+ label: 'Career & Skills',
+ description: 'Professional expertise and growth areas',
+ icon: Briefcase,
+ color: 'emerald'
+ },
+ non_negotiables: {
+ id: 'non_negotiables',
+ label: 'Non-Negotiables',
+ description: 'Principles and boundaries that define your limits',
+ icon: Shield,
+ color: 'red'
+ },
+ decision_heuristics: {
+ id: 'decision_heuristics',
+ label: 'Decision Heuristics',
+ description: 'Mental models and shortcuts for making choices',
+ icon: GitBranch,
+ color: 'indigo'
+ },
+ error_intolerance: {
+ id: 'error_intolerance',
+ label: 'Error Intolerance',
+ description: 'What your digital twin should never do',
+ icon: AlertOctagon,
+ color: 'rose'
+ }
+};
+
+// Export format configurations
+export const EXPORT_FORMATS = {
+ system_prompt: {
+ id: 'system_prompt',
+ label: 'System Prompt',
+ description: 'Combined markdown for direct injection into LLM system prompts'
+ },
+ claude_md: {
+ id: 'claude_md',
+ label: 'CLAUDE.md',
+ description: 'Format optimized for Claude Code integration'
+ },
+ json: {
+ id: 'json',
+ label: 'JSON',
+ description: 'Structured JSON for API integration'
+ },
+ individual: {
+ id: 'individual',
+ label: 'Individual Files',
+ description: 'Separate files for each document'
+ }
+};
+
+// Health score thresholds
+export const HEALTH_THRESHOLDS = {
+ excellent: 80,
+ good: 60,
+ fair: 40
+};
+
+export function getHealthColor(score) {
+ if (score >= HEALTH_THRESHOLDS.excellent) return 'text-green-400';
+ if (score >= HEALTH_THRESHOLDS.good) return 'text-blue-400';
+ if (score >= HEALTH_THRESHOLDS.fair) return 'text-yellow-400';
+ return 'text-red-400';
+}
+
+export function getHealthLabel(score) {
+ if (score >= HEALTH_THRESHOLDS.excellent) return 'Excellent';
+ if (score >= HEALTH_THRESHOLDS.good) return 'Good';
+ if (score >= HEALTH_THRESHOLDS.fair) return 'Fair';
+ return 'Needs Work';
+}
+
+// Format relative time
+export function formatRelativeTime(dateString) {
+ if (!dateString) return 'Never';
+
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now - date;
+ const diffMins = Math.floor(diffMs / 60000);
+ const diffHours = Math.floor(diffMs / 3600000);
+ const diffDays = Math.floor(diffMs / 86400000);
+
+ if (diffMins < 1) return 'Just now';
+ if (diffMins < 60) return `${diffMins}m ago`;
+ if (diffHours < 24) return `${diffHours}h ago`;
+ if (diffDays < 7) return `${diffDays}d ago`;
+
+ return date.toLocaleDateString();
+}
diff --git a/client/src/components/soul/tabs/DocumentsTab.jsx b/client/src/components/soul/tabs/DocumentsTab.jsx
new file mode 100644
index 0000000000..1ff7a664f6
--- /dev/null
+++ b/client/src/components/soul/tabs/DocumentsTab.jsx
@@ -0,0 +1,386 @@
+import { useState, useEffect } from 'react';
+import {
+ FileText,
+ Plus,
+ Trash2,
+ Save,
+ X,
+ Eye,
+ Edit2,
+ Check,
+ ToggleLeft,
+ ToggleRight,
+ Scale
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from 'react-hot-toast';
+
+import { DOCUMENT_CATEGORIES, formatRelativeTime } from '../constants';
+
+export default function DocumentsTab({ onRefresh }) {
+ const [documents, setDocuments] = useState([]);
+ const [selectedDoc, setSelectedDoc] = useState(null);
+ const [editMode, setEditMode] = useState(false);
+ const [editContent, setEditContent] = useState('');
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [showCreate, setShowCreate] = useState(false);
+ const [newDoc, setNewDoc] = useState({ filename: '', title: '', category: 'core', content: '' });
+ const [deleteConfirm, setDeleteConfirm] = useState(null);
+
+ useEffect(() => {
+ loadDocuments();
+ }, []);
+
+ const loadDocuments = async () => {
+ setLoading(true);
+ const docs = await api.getSoulDocuments().catch(() => []);
+ setDocuments(docs);
+ setLoading(false);
+ };
+
+ const loadDocument = async (id) => {
+ const doc = await api.getSoulDocument(id);
+ setSelectedDoc(doc);
+ setEditContent(doc.content);
+ setEditMode(false);
+ };
+
+ const handleSave = async () => {
+ if (!selectedDoc) return;
+ setSaving(true);
+ await api.updateSoulDocument(selectedDoc.id, { content: editContent });
+ toast.success('Document saved');
+ await loadDocuments();
+ await loadDocument(selectedDoc.id);
+ setEditMode(false);
+ setSaving(false);
+ onRefresh();
+ };
+
+ const handleToggleEnabled = async (doc, enabled) => {
+ await api.updateSoulDocument(doc.id, { enabled });
+ toast.success(enabled ? 'Document enabled' : 'Document disabled');
+ await loadDocuments();
+ if (selectedDoc?.id === doc.id) {
+ await loadDocument(doc.id);
+ }
+ onRefresh();
+ };
+
+ const handleWeightChange = async (doc, weight) => {
+ await api.updateSoulDocument(doc.id, { weight });
+ toast.success(`Weight set to ${weight}`);
+ await loadDocuments();
+ if (selectedDoc?.id === doc.id) {
+ setSelectedDoc({ ...selectedDoc, weight });
+ }
+ onRefresh();
+ };
+
+ const handleCreate = async () => {
+ if (!newDoc.filename || !newDoc.title || !newDoc.content) {
+ toast.error('All fields are required');
+ return;
+ }
+
+ const filename = newDoc.filename.endsWith('.md') ? newDoc.filename : `${newDoc.filename}.md`;
+
+ setSaving(true);
+ await api.createSoulDocument({
+ ...newDoc,
+ filename
+ });
+ toast.success('Document created');
+ await loadDocuments();
+ setShowCreate(false);
+ setNewDoc({ filename: '', title: '', category: 'core', content: '' });
+ setSaving(false);
+ onRefresh();
+ };
+
+ const handleDelete = async (id) => {
+ await api.deleteSoulDocument(id);
+ toast.success('Document deleted');
+ if (selectedDoc?.id === id) {
+ setSelectedDoc(null);
+ }
+ setDeleteConfirm(null);
+ await loadDocuments();
+ onRefresh();
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <div className="text-gray-500">Loading documents...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-full gap-4">
+ {/* Document List Sidebar */}
+ <div className="w-72 flex-shrink-0 bg-port-card rounded-lg border border-port-border overflow-hidden flex flex-col">
+ <div className="p-3 border-b border-port-border flex items-center justify-between">
+ <h3 className="font-medium text-white">Documents</h3>
+ <button
+ onClick={() => setShowCreate(true)}
+ className="p-1.5 text-gray-400 hover:text-white transition-colors"
+ title="Create document"
+ >
+ <Plus size={18} />
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto">
+ {documents.length === 0 ? (
+ <div className="p-4 text-center text-gray-500">
+ No documents yet
+ </div>
+ ) : (
+ Object.entries(DOCUMENT_CATEGORIES).map(([category, config]) => {
+ const categoryDocs = documents.filter(d => d.category === category);
+ if (categoryDocs.length === 0) return null;
+
+ return (
+ <div key={category} className="border-b border-port-border last:border-b-0">
+ <div className={`px-3 py-2 text-xs font-medium ${config.color} border-l-2`}>
+ {config.label}
+ </div>
+ {categoryDocs.map(doc => (
+ <button
+ key={doc.id}
+ onClick={() => loadDocument(doc.id)}
+ className={`w-full px-3 py-2 text-left hover:bg-port-border transition-colors ${
+ selectedDoc?.id === doc.id ? 'bg-port-accent/10 border-l-2 border-port-accent' : ''
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ <FileText size={14} className={doc.enabled ? 'text-white' : 'text-gray-500'} />
+ <span className={`text-sm truncate ${doc.enabled ? 'text-white' : 'text-gray-500'}`}>
+ {doc.title}
+ </span>
+ </div>
+ <div className="text-xs text-gray-500 mt-1">
+ {formatRelativeTime(doc.lastModified)}
+ </div>
+ </button>
+ ))}
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+
+ {/* Document Editor */}
+ <div className="flex-1 bg-port-card rounded-lg border border-port-border overflow-hidden flex flex-col">
+ {selectedDoc ? (
+ <>
+ {/* Editor Header */}
+ <div className="p-3 border-b border-port-border flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <h3 className="font-medium text-white">{selectedDoc.title}</h3>
+ <span className={`text-xs px-2 py-0.5 rounded ${DOCUMENT_CATEGORIES[selectedDoc.category]?.color}`}>
+ {DOCUMENT_CATEGORIES[selectedDoc.category]?.label}
+ </span>
+ {selectedDoc.version && (
+ <span className="text-xs text-gray-500">v{selectedDoc.version}</span>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ {/* Weight Control */}
+ <div className="flex items-center gap-2 px-2 py-1 bg-port-bg rounded border border-port-border" title="Document weight (1-10): Higher weight = included first when truncating">
+ <Scale size={14} className="text-gray-500" />
+ <input
+ type="range"
+ min="1"
+ max="10"
+ value={selectedDoc.weight || 5}
+ onChange={(e) => handleWeightChange(selectedDoc, parseInt(e.target.value))}
+ className="w-16 h-1 accent-port-accent"
+ />
+ <span className="text-xs text-gray-400 w-4">{selectedDoc.weight || 5}</span>
+ </div>
+ <button
+ onClick={() => handleToggleEnabled(selectedDoc, !selectedDoc.enabled)}
+ className={`p-1.5 transition-colors ${
+ selectedDoc.enabled ? 'text-green-400' : 'text-gray-500'
+ }`}
+ title={selectedDoc.enabled ? 'Disable for CoS injection' : 'Enable for CoS injection'}
+ >
+ {selectedDoc.enabled ? <ToggleRight size={20} /> : <ToggleLeft size={20} />}
+ </button>
+ {editMode ? (
+ <>
+ <button
+ onClick={handleSave}
+ disabled={saving}
+ className="p-1.5 text-green-400 hover:text-green-300 transition-colors disabled:opacity-50"
+ title="Save"
+ >
+ <Save size={18} />
+ </button>
+ <button
+ onClick={() => {
+ setEditContent(selectedDoc.content);
+ setEditMode(false);
+ }}
+ className="p-1.5 text-gray-400 hover:text-white transition-colors"
+ title="Cancel"
+ >
+ <X size={18} />
+ </button>
+ </>
+ ) : (
+ <>
+ <button
+ onClick={() => setEditMode(true)}
+ className="p-1.5 text-gray-400 hover:text-white transition-colors"
+ title="Edit"
+ >
+ <Edit2 size={18} />
+ </button>
+ <button
+ onClick={() => setDeleteConfirm(selectedDoc.id)}
+ className="p-1.5 text-gray-400 hover:text-red-400 transition-colors"
+ title="Delete"
+ >
+ <Trash2 size={18} />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Editor Content */}
+ <div className="flex-1 overflow-auto">
+ {editMode ? (
+ <textarea
+ value={editContent}
+ onChange={(e) => setEditContent(e.target.value)}
+ className="w-full h-full p-4 bg-port-bg text-white font-mono text-sm resize-none focus:outline-none"
+ placeholder="Write your soul document here..."
+ />
+ ) : (
+ <pre className="p-4 text-sm text-gray-300 whitespace-pre-wrap font-mono">
+ {selectedDoc.content}
+ </pre>
+ )}
+ </div>
+ </>
+ ) : (
+ <div className="flex-1 flex items-center justify-center text-gray-500">
+ <div className="text-center">
+ <FileText className="w-12 h-12 mx-auto mb-4 opacity-50" />
+ <p>Select a document to view or edit</p>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Create Document Modal */}
+ {showCreate && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
+ <div className="bg-port-card rounded-lg border border-port-border w-full max-w-lg p-6">
+ <h2 className="text-lg font-semibold text-white mb-4">Create Soul Document</h2>
+
+ <div className="space-y-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Filename</label>
+ <input
+ type="text"
+ value={newDoc.filename}
+ onChange={(e) => setNewDoc({ ...newDoc, filename: e.target.value })}
+ placeholder="DOCUMENT_NAME.md"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Title</label>
+ <input
+ type="text"
+ value={newDoc.title}
+ onChange={(e) => setNewDoc({ ...newDoc, title: e.target.value })}
+ placeholder="Document title"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Category</label>
+ <select
+ value={newDoc.category}
+ onChange={(e) => setNewDoc({ ...newDoc, category: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ {Object.entries(DOCUMENT_CATEGORIES).map(([key, config]) => (
+ <option key={key} value={key}>{config.label}</option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Content</label>
+ <textarea
+ value={newDoc.content}
+ onChange={(e) => setNewDoc({ ...newDoc, content: e.target.value })}
+ placeholder="# Document Title&#10;&#10;Content here..."
+ rows={10}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white font-mono text-sm"
+ />
+ </div>
+ </div>
+
+ <div className="flex justify-end gap-3 mt-6">
+ <button
+ onClick={() => {
+ setShowCreate(false);
+ setNewDoc({ filename: '', title: '', category: 'core', content: '' });
+ }}
+ className="px-4 py-2 text-gray-400 hover:text-white transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleCreate}
+ disabled={saving}
+ className="px-4 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ {saving ? 'Creating...' : 'Create'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Delete Confirmation Modal */}
+ {deleteConfirm && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
+ <div className="bg-port-card rounded-lg border border-port-border p-6 max-w-md">
+ <h2 className="text-lg font-semibold text-white mb-2">Delete Document?</h2>
+ <p className="text-gray-400 mb-6">
+ This action cannot be undone. The document will be permanently deleted.
+ </p>
+ <div className="flex justify-end gap-3">
+ <button
+ onClick={() => setDeleteConfirm(null)}
+ className="px-4 py-2 text-gray-400 hover:text-white transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={() => handleDelete(deleteConfirm)}
+ className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
+ >
+ Delete
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/soul/tabs/EnrichTab.jsx b/client/src/components/soul/tabs/EnrichTab.jsx
new file mode 100644
index 0000000000..93ad092341
--- /dev/null
+++ b/client/src/components/soul/tabs/EnrichTab.jsx
@@ -0,0 +1,570 @@
+import { useState, useEffect } from 'react';
+import {
+ Sparkles,
+ ChevronRight,
+ Check,
+ Send,
+ SkipForward,
+ RefreshCw,
+ ArrowLeft,
+ FileText,
+ PenTool,
+ Eye,
+ Save
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from 'react-hot-toast';
+
+import { ENRICHMENT_CATEGORIES } from '../constants';
+
+export default function EnrichTab({ onRefresh }) {
+ const [categories, setCategories] = useState([]);
+ const [progress, setProgress] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ // Active session state
+ const [activeCategory, setActiveCategory] = useState(null);
+ const [currentQuestion, setCurrentQuestion] = useState(null);
+ const [answer, setAnswer] = useState('');
+ const [submitting, setSubmitting] = useState(false);
+ const [loadingQuestion, setLoadingQuestion] = useState(false);
+
+ // Writing sample analysis
+ const [showWritingAnalysis, setShowWritingAnalysis] = useState(false);
+ const [writingSamples, setWritingSamples] = useState(['']);
+ const [analyzingWriting, setAnalyzingWriting] = useState(false);
+ const [writingAnalysis, setWritingAnalysis] = useState(null);
+ const [providers, setProviders] = useState([]);
+ const [selectedProvider, setSelectedProvider] = useState(null);
+ const [savingWritingStyle, setSavingWritingStyle] = useState(false);
+
+ useEffect(() => {
+ loadData();
+ loadProviders();
+ }, []);
+
+ const loadData = async () => {
+ setLoading(true);
+ const [categoriesData, progressData] = await Promise.all([
+ api.getSoulEnrichCategories().catch(() => []),
+ api.getSoulEnrichProgress().catch(() => null)
+ ]);
+ setCategories(categoriesData);
+ setProgress(progressData);
+ setLoading(false);
+ };
+
+ const loadProviders = async () => {
+ const data = await api.getProviders().catch(() => ({ providers: [] }));
+ const enabled = (data.providers || []).filter(p => p.enabled);
+ setProviders(enabled);
+ if (enabled.length > 0) {
+ setSelectedProvider({ providerId: enabled[0].id, model: enabled[0].defaultModel });
+ }
+ };
+
+ const addWritingSample = () => {
+ setWritingSamples([...writingSamples, '']);
+ };
+
+ const updateWritingSample = (index, value) => {
+ const updated = [...writingSamples];
+ updated[index] = value;
+ setWritingSamples(updated);
+ };
+
+ const removeWritingSample = (index) => {
+ if (writingSamples.length > 1) {
+ setWritingSamples(writingSamples.filter((_, i) => i !== index));
+ }
+ };
+
+ const analyzeWriting = async () => {
+ const validSamples = writingSamples.filter(s => s.trim().length >= 50);
+ if (validSamples.length === 0) {
+ toast.error('Add at least one writing sample (50+ characters)');
+ return;
+ }
+ if (!selectedProvider) {
+ toast.error('Select a provider first');
+ return;
+ }
+
+ setAnalyzingWriting(true);
+ const result = await api.analyzeWritingSamples(
+ validSamples,
+ selectedProvider.providerId,
+ selectedProvider.model
+ ).catch(e => ({ error: e.message }));
+
+ if (result.error) {
+ toast.error(result.error);
+ } else {
+ setWritingAnalysis(result);
+ toast.success('Writing analysis complete');
+ }
+ setAnalyzingWriting(false);
+ };
+
+ const saveWritingStyle = async () => {
+ if (!writingAnalysis?.suggestedContent) {
+ toast.error('No writing style content to save');
+ return;
+ }
+
+ setSavingWritingStyle(true);
+ await api.createSoulDocument({
+ filename: 'WRITING_STYLE.md',
+ title: 'Writing Style',
+ category: 'core',
+ content: writingAnalysis.suggestedContent
+ }).catch(async () => {
+ // Document might exist, try to update by fetching ID
+ const docs = await api.getSoulDocuments();
+ const existing = docs.find(d => d.filename === 'WRITING_STYLE.md');
+ if (existing) {
+ return api.updateSoulDocument(existing.id, {
+ content: writingAnalysis.suggestedContent
+ });
+ }
+ });
+ toast.success('Writing style saved');
+ setSavingWritingStyle(false);
+ onRefresh();
+ };
+
+ const startCategory = async (categoryId) => {
+ setActiveCategory(categoryId);
+ await loadQuestion(categoryId);
+ };
+
+ const loadQuestion = async (categoryId) => {
+ setLoadingQuestion(true);
+ const question = await api.getSoulEnrichQuestion(categoryId);
+ setCurrentQuestion(question);
+ setAnswer('');
+ setLoadingQuestion(false);
+ };
+
+ const submitAnswer = async () => {
+ if (!answer.trim()) {
+ toast.error('Please provide an answer');
+ return;
+ }
+
+ setSubmitting(true);
+ await api.submitSoulEnrichAnswer({
+ questionId: currentQuestion.questionId,
+ category: activeCategory,
+ question: currentQuestion.question,
+ answer: answer.trim()
+ });
+
+ toast.success('Answer saved');
+ await loadData();
+
+ // Load next question
+ await loadQuestion(activeCategory);
+ setSubmitting(false);
+ onRefresh();
+ };
+
+ const skipQuestion = async () => {
+ await loadQuestion(activeCategory);
+ };
+
+ const exitCategory = () => {
+ setActiveCategory(null);
+ setCurrentQuestion(null);
+ setAnswer('');
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ // Active enrichment session
+ if (activeCategory && currentQuestion) {
+ const categoryConfig = ENRICHMENT_CATEGORIES[activeCategory];
+ const categoryProgress = progress?.categories?.[activeCategory];
+ const Icon = categoryConfig?.icon || Sparkles;
+
+ return (
+ <div className="max-w-2xl mx-auto">
+ {/* Header */}
+ <div className="mb-8">
+ <button
+ onClick={exitCategory}
+ className="flex items-center gap-2 text-gray-400 hover:text-white mb-4"
+ >
+ <ArrowLeft size={18} />
+ Back to categories
+ </button>
+
+ <div className="flex items-center gap-4">
+ <div className={`p-3 rounded-lg bg-${categoryConfig?.color || 'blue'}-500/20`}>
+ <Icon className={`w-6 h-6 text-${categoryConfig?.color || 'blue'}-400`} />
+ </div>
+ <div>
+ <h2 className="text-xl font-bold text-white">{categoryConfig?.label}</h2>
+ <p className="text-gray-400">{categoryConfig?.description}</p>
+ </div>
+ </div>
+
+ {/* Progress bar */}
+ <div className="mt-4">
+ <div className="flex items-center justify-between text-sm mb-1">
+ <span className="text-gray-400">
+ Question {categoryProgress?.answered + 1 || 1}
+ {currentQuestion.totalQuestions && ` of ${currentQuestion.totalQuestions}`}
+ </span>
+ <span className="text-gray-400">{categoryProgress?.percentage || 0}% complete</span>
+ </div>
+ <div className="h-2 bg-port-border rounded-full overflow-hidden">
+ <div
+ className="h-full bg-port-accent transition-all"
+ style={{ width: `${categoryProgress?.percentage || 0}%` }}
+ />
+ </div>
+ </div>
+ </div>
+
+ {/* Question */}
+ {loadingQuestion ? (
+ <div className="flex items-center justify-center h-48">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ ) : (
+ <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'}
+ </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>
+ </div>
+
+ <div className="flex items-center justify-between">
+ <button
+ onClick={skipQuestion}
+ className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white transition-colors"
+ >
+ <SkipForward size={18} />
+ Skip
+ </button>
+
+ <button
+ onClick={submitAnswer}
+ disabled={submitting || !answer.trim()}
+ className="flex items-center gap-2 px-6 py-3 bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {submitting ? (
+ <>
+ <RefreshCw className="w-5 h-5 animate-spin" />
+ Saving...
+ </>
+ ) : (
+ <>
+ <Send size={18} />
+ Submit Answer
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Category completion */}
+ {categoryProgress?.completed && (
+ <div className="mt-6 p-4 bg-green-500/10 border border-green-500/30 rounded-lg">
+ <div className="flex items-center gap-3">
+ <Check className="w-5 h-5 text-green-400" />
+ <span className="text-green-400">
+ This category is complete! Continue answering to add more depth.
+ </span>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ // Category selection view
+ return (
+ <div className="space-y-6">
+ {/* Overall Progress */}
+ <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">Enrichment Progress</h2>
+ <span className="text-gray-400">
+ {progress?.completedCount || 0}/{progress?.totalCategories || 10} categories complete
+ </span>
+ </div>
+
+ <div className="h-3 bg-port-border rounded-full overflow-hidden">
+ <div
+ className="h-full bg-gradient-to-r from-yellow-500 to-orange-500 transition-all"
+ style={{ width: `${((progress?.completedCount || 0) / (progress?.totalCategories || 10)) * 100}%` }}
+ />
+ </div>
+
+ {progress?.lastSession && (
+ <p className="text-sm text-gray-500 mt-3">
+ Last session: {new Date(progress.lastSession).toLocaleDateString()}
+ </p>
+ )}
+ </div>
+
+ {/* Category Grid */}
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
+ {Object.entries(ENRICHMENT_CATEGORIES).map(([key, config]) => {
+ const catProgress = progress?.categories?.[key];
+ const isComplete = catProgress?.completed;
+ const Icon = config.icon;
+
+ return (
+ <button
+ key={key}
+ onClick={() => startCategory(key)}
+ className={`p-4 bg-port-card rounded-lg border transition-all text-left hover:border-port-accent ${
+ isComplete ? 'border-green-500/30' : 'border-port-border'
+ }`}
+ >
+ <div className="flex items-start justify-between mb-3">
+ <div className={`p-2 rounded-lg bg-${config.color}-500/20`}>
+ <Icon className={`w-5 h-5 text-${config.color}-400`} />
+ </div>
+ {isComplete ? (
+ <Check className="w-5 h-5 text-green-400" />
+ ) : (
+ <ChevronRight className="w-5 h-5 text-gray-500" />
+ )}
+ </div>
+
+ <h3 className="font-semibold text-white mb-1">{config.label}</h3>
+ <p className="text-sm text-gray-400 mb-3">{config.description}</p>
+
+ <div className="flex items-center justify-between text-xs">
+ <span className="text-gray-500">
+ {catProgress?.answered || 0} questions answered
+ </span>
+ <span className={isComplete ? 'text-green-400' : 'text-gray-500'}>
+ {catProgress?.percentage || 0}%
+ </span>
+ </div>
+
+ {/* Mini progress bar */}
+ <div className="h-1 bg-port-border rounded-full mt-2 overflow-hidden">
+ <div
+ className={`h-full transition-all ${isComplete ? 'bg-green-500' : 'bg-port-accent'}`}
+ style={{ width: `${catProgress?.percentage || 0}%` }}
+ />
+ </div>
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Info */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <div className="flex items-start gap-4">
+ <Sparkles className="w-6 h-6 text-yellow-400 flex-shrink-0" />
+ <div>
+ <h3 className="font-medium text-white mb-1">How Enrichment Works</h3>
+ <p className="text-sm text-gray-400">
+ Answer questions in each category to build a comprehensive profile. After answering
+ the core questions (3 per category), AI-generated follow-up questions will help
+ capture more nuanced details. Your answers are processed and added to your soul documents.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ {/* Writing Sample Analysis */}
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
+ <button
+ onClick={() => setShowWritingAnalysis(!showWritingAnalysis)}
+ className="w-full p-4 flex items-center justify-between hover:bg-port-border/30 transition-colors"
+ >
+ <div className="flex items-center gap-3">
+ <PenTool className="w-6 h-6 text-cyan-400" />
+ <div className="text-left">
+ <h3 className="font-medium text-white">Analyze Your Writing</h3>
+ <p className="text-sm text-gray-400">Extract communication patterns from your actual writing</p>
+ </div>
+ </div>
+ <ChevronRight className={`w-5 h-5 text-gray-400 transition-transform ${showWritingAnalysis ? 'rotate-90' : ''}`} />
+ </button>
+
+ {showWritingAnalysis && (
+ <div className="p-4 pt-0 space-y-4">
+ <p className="text-sm text-gray-400">
+ Paste samples of your writing (emails, messages, documents) to extract your authentic voice patterns.
+ The AI will analyze sentence structure, vocabulary, tone, and distinctive markers.
+ </p>
+
+ {/* Provider Selection */}
+ <div className="flex items-center gap-4">
+ <label className="text-sm text-gray-400">Analyze with:</label>
+ <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"
+ >
+ {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>
+ </div>
+
+ {/* Writing Samples */}
+ <div className="space-y-3">
+ {writingSamples.map((sample, index) => (
+ <div key={index} className="relative">
+ <textarea
+ value={sample}
+ onChange={(e) => updateWritingSample(index, e.target.value)}
+ placeholder={`Paste writing sample ${index + 1} here (emails, messages, docs)...`}
+ rows={4}
+ 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"
+ />
+ {writingSamples.length > 1 && (
+ <button
+ onClick={() => removeWritingSample(index)}
+ className="absolute top-2 right-2 text-gray-500 hover:text-red-400"
+ >
+ ×
+ </button>
+ )}
+ <div className="text-xs text-gray-500 mt-1">
+ {sample.length} characters {sample.length < 50 && sample.length > 0 && '(need 50+)'}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ <div className="flex items-center gap-4">
+ <button
+ onClick={addWritingSample}
+ className="px-4 py-2 text-sm text-port-accent hover:text-white border border-port-accent/30 rounded-lg hover:border-port-accent"
+ >
+ + Add Another Sample
+ </button>
+
+ <button
+ onClick={analyzeWriting}
+ disabled={analyzingWriting}
+ className="px-4 py-2 bg-cyan-600 text-white rounded-lg text-sm hover:bg-cyan-500 disabled:opacity-50 flex items-center gap-2"
+ >
+ {analyzingWriting ? (
+ <>
+ <RefreshCw className="w-4 h-4 animate-spin" />
+ Analyzing...
+ </>
+ ) : (
+ <>
+ <Eye className="w-4 h-4" />
+ Analyze Writing
+ </>
+ )}
+ </button>
+ </div>
+
+ {/* Analysis Results */}
+ {writingAnalysis && (
+ <div className="mt-4 pt-4 border-t border-port-border space-y-4">
+ <h4 className="font-medium text-white flex items-center gap-2">
+ <FileText className="w-4 h-4" />
+ Analysis Results
+ </h4>
+
+ {writingAnalysis.analysis && (
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
+ {writingAnalysis.analysis.formality && (
+ <div className="p-3 bg-port-bg rounded-lg">
+ <div className="text-xs text-gray-500">Formality</div>
+ <div className="text-white capitalize">{writingAnalysis.analysis.formality}</div>
+ </div>
+ )}
+ {writingAnalysis.analysis.directness && (
+ <div className="p-3 bg-port-bg rounded-lg">
+ <div className="text-xs text-gray-500">Directness</div>
+ <div className="text-white">{writingAnalysis.analysis.directness}/10</div>
+ </div>
+ )}
+ {writingAnalysis.analysis.warmth && (
+ <div className="p-3 bg-port-bg rounded-lg">
+ <div className="text-xs text-gray-500">Warmth</div>
+ <div className="text-white">{writingAnalysis.analysis.warmth}/10</div>
+ </div>
+ )}
+ {writingAnalysis.analysis.humor && (
+ <div className="p-3 bg-port-bg rounded-lg">
+ <div className="text-xs text-gray-500">Humor</div>
+ <div className="text-white capitalize">{writingAnalysis.analysis.humor}</div>
+ </div>
+ )}
+ </div>
+ )}
+
+ {writingAnalysis.analysis?.overallVoice && (
+ <div className="p-3 bg-port-bg rounded-lg">
+ <div className="text-xs text-gray-500 mb-1">Overall Voice</div>
+ <div className="text-white text-sm">{writingAnalysis.analysis.overallVoice}</div>
+ </div>
+ )}
+
+ {writingAnalysis.suggestedContent && (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <div className="text-sm text-gray-400">Suggested WRITING_STYLE.md content:</div>
+ <button
+ onClick={saveWritingStyle}
+ disabled={savingWritingStyle}
+ className="px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-500 disabled:opacity-50 flex items-center gap-1"
+ >
+ {savingWritingStyle ? (
+ <RefreshCw className="w-3 h-3 animate-spin" />
+ ) : (
+ <Save className="w-3 h-3" />
+ )}
+ Save to Soul
+ </button>
+ </div>
+ <pre className="p-3 bg-port-bg rounded-lg text-sm text-gray-300 whitespace-pre-wrap overflow-auto max-h-64">
+ {writingAnalysis.suggestedContent}
+ </pre>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/soul/tabs/ExportTab.jsx b/client/src/components/soul/tabs/ExportTab.jsx
new file mode 100644
index 0000000000..4078050a1e
--- /dev/null
+++ b/client/src/components/soul/tabs/ExportTab.jsx
@@ -0,0 +1,339 @@
+import { useState, useEffect } from 'react';
+import {
+ Download,
+ Copy,
+ Check,
+ FileText,
+ Code,
+ FileJson,
+ Files,
+ RefreshCw,
+ Eye
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from 'react-hot-toast';
+
+import { EXPORT_FORMATS, DOCUMENT_CATEGORIES } from '../constants';
+
+export default function ExportTab({ onRefresh }) {
+ const [documents, setDocuments] = useState([]);
+ const [formats, setFormats] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [exporting, setExporting] = useState(false);
+
+ // Export configuration
+ const [selectedFormat, setSelectedFormat] = useState('system_prompt');
+ const [selectedDocs, setSelectedDocs] = useState([]);
+ const [includeDisabled, setIncludeDisabled] = useState(false);
+
+ // Export result
+ const [exportResult, setExportResult] = useState(null);
+ const [copied, setCopied] = useState(false);
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ const loadData = async () => {
+ setLoading(true);
+ const [docsData, formatsData] = await Promise.all([
+ api.getSoulDocuments().catch(() => []),
+ api.getSoulExportFormats().catch(() => [])
+ ]);
+ setDocuments(docsData);
+ setFormats(formatsData);
+
+ // Default: select all enabled documents
+ setSelectedDocs(docsData.filter(d => d.enabled).map(d => d.id));
+
+ setLoading(false);
+ };
+
+ const toggleDocument = (docId) => {
+ setSelectedDocs(prev =>
+ prev.includes(docId) ? prev.filter(id => id !== docId) : [...prev, docId]
+ );
+ };
+
+ const handleExport = async () => {
+ setExporting(true);
+ const result = await api.exportSoul(
+ selectedFormat,
+ selectedDocs.length > 0 ? selectedDocs : null,
+ includeDisabled
+ );
+ setExportResult(result);
+ setExporting(false);
+ };
+
+ const copyToClipboard = async () => {
+ if (!exportResult) return;
+
+ const content = typeof exportResult.content === 'string'
+ ? exportResult.content
+ : JSON.stringify(exportResult.content, null, 2);
+
+ await navigator.clipboard.writeText(content);
+ setCopied(true);
+ toast.success('Copied to clipboard');
+ setTimeout(() => setCopied(false), 2000);
+ };
+
+ const downloadFile = () => {
+ if (!exportResult) return;
+
+ const content = typeof exportResult.content === 'string'
+ ? exportResult.content
+ : JSON.stringify(exportResult.content, null, 2);
+
+ const extension = selectedFormat === 'json' ? 'json' : 'md';
+ const filename = `soul-export.${extension}`;
+
+ const blob = new Blob([content], { type: 'text/plain' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+
+ toast.success(`Downloaded ${filename}`);
+ };
+
+ const getFormatIcon = (formatId) => {
+ switch (formatId) {
+ case 'system_prompt':
+ return FileText;
+ case 'claude_md':
+ return Code;
+ case 'json':
+ return FileJson;
+ case 'individual':
+ return Files;
+ default:
+ return FileText;
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ {/* Configuration */}
+ <div className="space-y-6">
+ {/* Format Selection */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <h3 className="font-semibold text-white mb-4">Export Format</h3>
+ <div className="space-y-2">
+ {formats.map(format => {
+ const Icon = getFormatIcon(format.id);
+ return (
+ <button
+ key={format.id}
+ onClick={() => {
+ setSelectedFormat(format.id);
+ setExportResult(null);
+ }}
+ className={`w-full flex items-start gap-3 p-3 rounded-lg border transition-colors text-left ${
+ selectedFormat === format.id
+ ? 'border-port-accent bg-port-accent/10'
+ : 'border-port-border hover:border-gray-500'
+ }`}
+ >
+ <Icon className={`w-5 h-5 mt-0.5 ${
+ selectedFormat === format.id ? 'text-port-accent' : 'text-gray-400'
+ }`} />
+ <div>
+ <div className={`font-medium ${
+ selectedFormat === format.id ? 'text-port-accent' : 'text-white'
+ }`}>
+ {format.label}
+ </div>
+ <div className="text-sm text-gray-400">{format.description}</div>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Document Selection */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="font-semibold text-white">Documents ({selectedDocs.length})</h3>
+ <div className="flex gap-2">
+ <button
+ onClick={() => setSelectedDocs(documents.map(d => d.id))}
+ className="text-xs text-port-accent hover:text-white"
+ >
+ All
+ </button>
+ <button
+ onClick={() => setSelectedDocs(documents.filter(d => d.enabled).map(d => d.id))}
+ className="text-xs text-gray-500 hover:text-white"
+ >
+ Enabled
+ </button>
+ <button
+ onClick={() => setSelectedDocs([])}
+ className="text-xs text-gray-500 hover:text-white"
+ >
+ None
+ </button>
+ </div>
+ </div>
+
+ <div className="space-y-2 max-h-64 overflow-y-auto">
+ {documents.map(doc => (
+ <label
+ key={doc.id}
+ className="flex items-center gap-3 p-2 rounded hover:bg-port-border cursor-pointer"
+ >
+ <input
+ type="checkbox"
+ checked={selectedDocs.includes(doc.id)}
+ onChange={() => toggleDocument(doc.id)}
+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ <div className="flex-1 min-w-0">
+ <div className={`text-sm truncate ${doc.enabled ? 'text-white' : 'text-gray-500'}`}>
+ {doc.title}
+ </div>
+ <div className="text-xs text-gray-500">
+ {DOCUMENT_CATEGORIES[doc.category]?.label}
+ {!doc.enabled && ' • Disabled'}
+ </div>
+ </div>
+ </label>
+ ))}
+ </div>
+
+ <label className="flex items-center gap-2 mt-4 pt-4 border-t border-port-border">
+ <input
+ type="checkbox"
+ checked={includeDisabled}
+ onChange={(e) => setIncludeDisabled(e.target.checked)}
+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ <span className="text-sm text-gray-400">Include disabled documents</span>
+ </label>
+ </div>
+
+ {/* Export Button */}
+ <button
+ onClick={handleExport}
+ disabled={exporting || selectedDocs.length === 0}
+ className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {exporting ? (
+ <>
+ <RefreshCw className="w-5 h-5 animate-spin" />
+ Exporting...
+ </>
+ ) : (
+ <>
+ <Download className="w-5 h-5" />
+ Generate Export
+ </>
+ )}
+ </button>
+ </div>
+
+ {/* Preview / Result */}
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden flex flex-col">
+ <div className="p-4 border-b border-port-border flex items-center justify-between">
+ <h3 className="font-semibold text-white flex items-center gap-2">
+ <Eye size={18} />
+ Preview
+ </h3>
+
+ {exportResult && (
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-gray-500">
+ ~{exportResult.tokenEstimate?.toLocaleString()} tokens
+ </span>
+ <button
+ onClick={copyToClipboard}
+ className="p-1.5 text-gray-400 hover:text-white transition-colors"
+ title="Copy to clipboard"
+ >
+ {copied ? <Check size={18} className="text-green-400" /> : <Copy size={18} />}
+ </button>
+ <button
+ onClick={downloadFile}
+ className="p-1.5 text-gray-400 hover:text-white transition-colors"
+ title="Download"
+ >
+ <Download size={18} />
+ </button>
+ </div>
+ )}
+ </div>
+
+ <div className="flex-1 overflow-auto p-4">
+ {exportResult ? (
+ <pre className="text-sm text-gray-300 whitespace-pre-wrap font-mono">
+ {typeof exportResult.content === 'string'
+ ? exportResult.content
+ : JSON.stringify(exportResult.content, null, 2)}
+ </pre>
+ ) : (
+ <div className="flex items-center justify-center h-full text-gray-500">
+ <div className="text-center">
+ <Download className="w-12 h-12 mx-auto mb-4 opacity-50" />
+ <p>Select options and generate export</p>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Usage Instructions */}
+ {exportResult && (
+ <div className="lg:col-span-2 bg-port-card rounded-lg border border-port-border p-4">
+ <h3 className="font-semibold text-white mb-3">How to Use</h3>
+
+ {selectedFormat === 'system_prompt' && (
+ <div className="text-sm text-gray-400 space-y-2">
+ <p>1. Copy the exported content</p>
+ <p>2. Paste into your LLMs system prompt / custom instructions</p>
+ <p>3. The LLM will now respond according to your soul document</p>
+ </div>
+ )}
+
+ {selectedFormat === 'claude_md' && (
+ <div className="text-sm text-gray-400 space-y-2">
+ <p>1. Download or copy the export</p>
+ <p>2. Add to your project as <code className="bg-port-bg px-1 rounded">CLAUDE.md</code></p>
+ <p>3. Claude Code will automatically read and apply these instructions</p>
+ </div>
+ )}
+
+ {selectedFormat === 'json' && (
+ <div className="text-sm text-gray-400 space-y-2">
+ <p>1. Download the JSON export</p>
+ <p>2. Parse and inject into your API requests</p>
+ <p>3. Use the documents array to build system prompts programmatically</p>
+ </div>
+ )}
+
+ {selectedFormat === 'individual' && (
+ <div className="text-sm text-gray-400 space-y-2">
+ <p>1. Each document is exported separately</p>
+ <p>2. Use individual files for selective context injection</p>
+ <p>3. Combine as needed for different use cases</p>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/soul/tabs/OverviewTab.jsx b/client/src/components/soul/tabs/OverviewTab.jsx
new file mode 100644
index 0000000000..005e51d81e
--- /dev/null
+++ b/client/src/components/soul/tabs/OverviewTab.jsx
@@ -0,0 +1,552 @@
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import {
+ Heart,
+ FileText,
+ CheckCircle,
+ Sparkles,
+ Download,
+ Play,
+ Settings,
+ AlertCircle,
+ AlertTriangle,
+ Target,
+ RefreshCw,
+ ChevronRight
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from 'react-hot-toast';
+
+import {
+ DOCUMENT_CATEGORIES,
+ getHealthColor,
+ getHealthLabel,
+ formatRelativeTime
+} from '../constants';
+import SoulWizard from '../SoulWizard';
+
+export default function OverviewTab({ status, settings, onRefresh }) {
+ const navigate = useNavigate();
+ const [showSettings, setShowSettings] = useState(false);
+ const [settingsForm, setSettingsForm] = useState(settings || {});
+ const [saving, setSaving] = useState(false);
+ const [completeness, setCompleteness] = useState(null);
+ const [loadingCompleteness, setLoadingCompleteness] = useState(false);
+ const [showValidation, setShowValidation] = useState(false);
+ const [contradictions, setContradictions] = useState(null);
+ const [checkingContradictions, setCheckingContradictions] = useState(false);
+ const [providers, setProviders] = useState([]);
+ const [selectedProvider, setSelectedProvider] = useState(null);
+ const [showWizard, setShowWizard] = useState(false);
+
+ useEffect(() => {
+ loadCompleteness();
+ loadProviders();
+ }, []);
+
+ const loadCompleteness = async () => {
+ setLoadingCompleteness(true);
+ const data = await api.getSoulCompleteness().catch(() => null);
+ setCompleteness(data);
+ setLoadingCompleteness(false);
+ };
+
+ const loadProviders = async () => {
+ const data = await api.getProviders().catch(() => ({ providers: [] }));
+ const enabled = (data.providers || []).filter(p => p.enabled);
+ setProviders(enabled);
+ if (enabled.length > 0) {
+ setSelectedProvider({ providerId: enabled[0].id, model: enabled[0].defaultModel });
+ }
+ };
+
+ const checkContradictions = async () => {
+ if (!selectedProvider) {
+ toast.error('Select a provider first');
+ return;
+ }
+ setCheckingContradictions(true);
+ const result = await api.detectSoulContradictions(
+ selectedProvider.providerId,
+ selectedProvider.model
+ ).catch(e => ({ error: e.message }));
+ setContradictions(result);
+ setCheckingContradictions(false);
+ };
+
+ const isEmpty = !status || status.documentCount === 0;
+
+ const handleSaveSettings = async () => {
+ setSaving(true);
+ await api.updateSoulSettings(settingsForm);
+ toast.success('Settings updated');
+ setSaving(false);
+ setShowSettings(false);
+ onRefresh();
+ };
+
+ if (isEmpty) {
+ if (showWizard) {
+ return (
+ <div className="max-w-2xl mx-auto p-8">
+ <SoulWizard
+ onComplete={() => {
+ setShowWizard(false);
+ onRefresh();
+ }}
+ onCancel={() => setShowWizard(false)}
+ />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col items-center justify-center h-full max-w-2xl mx-auto text-center p-8">
+ <Heart className="w-16 h-16 text-pink-500 mb-6" />
+ <h2 className="text-2xl font-bold text-white mb-4">Create Your Digital Twin</h2>
+ <p className="text-gray-400 mb-8">
+ A soul document is a comprehensive identity scaffold that defines who you are -
+ your values, preferences, communication style, and cognitive patterns.
+ When loaded into an LLM, it creates a digital twin that thinks and responds like you.
+ </p>
+
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4 w-full mb-8">
+ <div className="p-4 bg-port-card rounded-lg border border-port-border">
+ <FileText className="w-8 h-8 text-purple-400 mb-3" />
+ <h3 className="font-semibold text-white mb-2">Core Identity</h3>
+ <p className="text-sm text-gray-400">Define your values, philosophy, and worldview</p>
+ </div>
+ <div className="p-4 bg-port-card rounded-lg border border-port-border">
+ <Sparkles className="w-8 h-8 text-yellow-400 mb-3" />
+ <h3 className="font-semibold text-white mb-2">Enrichment</h3>
+ <p className="text-sm text-gray-400">Answer questions to expand your profile</p>
+ </div>
+ <div className="p-4 bg-port-card rounded-lg border border-port-border">
+ <CheckCircle className="w-8 h-8 text-green-400 mb-3" />
+ <h3 className="font-semibold text-white mb-2">Testing</h3>
+ <p className="text-sm text-gray-400">Verify alignment across different models</p>
+ </div>
+ </div>
+
+ <div className="flex gap-4">
+ <button
+ onClick={() => setShowWizard(true)}
+ className="px-6 py-3 bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 transition-colors"
+ >
+ Start Wizard
+ </button>
+ <button
+ onClick={() => navigate('/soul/enrich')}
+ className="px-6 py-3 bg-port-card text-white rounded-lg font-medium border border-port-border hover:bg-port-border transition-colors"
+ >
+ Start Enrichment
+ </button>
+ <button
+ onClick={() => navigate('/soul/documents')}
+ className="px-6 py-3 bg-port-card text-white rounded-lg font-medium border border-port-border hover:bg-port-border transition-colors"
+ >
+ Create Document
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Health Score Card */}
+ <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">Soul Health</h2>
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ className="p-2 text-gray-400 hover:text-white transition-colors"
+ title="Settings"
+ >
+ <Settings size={20} />
+ </button>
+ </div>
+
+ <div className="flex items-center gap-6">
+ <div className="relative w-32 h-32">
+ <svg className="w-full h-full transform -rotate-90">
+ <circle
+ cx="64"
+ cy="64"
+ r="56"
+ stroke="currentColor"
+ strokeWidth="8"
+ fill="none"
+ className="text-port-border"
+ />
+ <circle
+ cx="64"
+ cy="64"
+ r="56"
+ stroke="currentColor"
+ strokeWidth="8"
+ fill="none"
+ strokeDasharray={`${status.healthScore * 3.52} 352`}
+ strokeLinecap="round"
+ className={getHealthColor(status.healthScore)}
+ />
+ </svg>
+ <div className="absolute inset-0 flex flex-col items-center justify-center">
+ <span className={`text-3xl font-bold ${getHealthColor(status.healthScore)}`}>
+ {status.healthScore}%
+ </span>
+ <span className="text-xs text-gray-500">
+ {getHealthLabel(status.healthScore)}
+ </span>
+ </div>
+ </div>
+
+ <div className="flex-1 grid grid-cols-3 gap-4">
+ <div>
+ <div className="text-2xl font-bold text-white">{status.enabledDocuments}</div>
+ <div className="text-sm text-gray-500">Active Documents</div>
+ </div>
+ <div>
+ <div className="text-2xl font-bold text-white">
+ {status.enrichmentProgress?.completedCategories || 0}/{status.enrichmentProgress?.totalCategories || 10}
+ </div>
+ <div className="text-sm text-gray-500">Enriched Categories</div>
+ </div>
+ <div>
+ <div className="text-2xl font-bold text-white">
+ {status.lastTestRun ? `${Math.round(status.lastTestRun.score * 100)}%` : '—'}
+ </div>
+ <div className="text-sm text-gray-500">Last Test Score</div>
+ </div>
+ </div>
+ </div>
+
+ {/* Settings Panel */}
+ {showSettings && (
+ <div className="mt-6 pt-6 border-t border-port-border">
+ <h3 className="text-sm font-medium text-gray-400 mb-4">Settings</h3>
+ <div className="space-y-4">
+ <label className="flex items-center gap-3">
+ <input
+ type="checkbox"
+ checked={settingsForm.autoInjectToCoS || false}
+ onChange={(e) => setSettingsForm({ ...settingsForm, autoInjectToCoS: e.target.checked })}
+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ <span className="text-white">Auto-inject soul context into CoS agents</span>
+ </label>
+ <div>
+ <label className="block text-sm text-gray-400 mb-2">Max context tokens</label>
+ <input
+ type="number"
+ value={settingsForm.maxContextTokens || 4000}
+ onChange={(e) => setSettingsForm({ ...settingsForm, maxContextTokens: parseInt(e.target.value) })}
+ className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ />
+ </div>
+ <button
+ onClick={handleSaveSettings}
+ disabled={saving}
+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ {saving ? 'Saving...' : 'Save Settings'}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Completeness Score */}
+ <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">
+ <Target size={20} />
+ Completeness
+ </h2>
+ <button
+ onClick={() => setShowValidation(!showValidation)}
+ className="text-sm text-port-accent hover:text-white transition-colors"
+ >
+ {showValidation ? 'Hide Details' : 'Show Details'}
+ </button>
+ </div>
+
+ {loadingCompleteness ? (
+ <div className="flex items-center gap-2 text-gray-400">
+ <RefreshCw className="w-4 h-4 animate-spin" />
+ Analyzing...
+ </div>
+ ) : completeness ? (
+ <div>
+ <div className="flex items-center gap-4 mb-4">
+ <div className={`text-3xl font-bold ${
+ completeness.score >= 80 ? 'text-green-400' :
+ completeness.score >= 50 ? 'text-yellow-400' : 'text-red-400'
+ }`}>
+ {completeness.score}%
+ </div>
+ <div>
+ <div className="text-white">{completeness.found}/{completeness.total} sections covered</div>
+ <div className="text-sm text-gray-500">
+ {completeness.missing.length === 0 ? 'All core sections present' : `${completeness.missing.length} sections missing`}
+ </div>
+ </div>
+ </div>
+
+ {/* Progress bar */}
+ <div className="h-2 bg-port-border rounded-full overflow-hidden mb-4">
+ <div
+ className={`h-full transition-all ${
+ completeness.score >= 80 ? 'bg-green-500' :
+ completeness.score >= 50 ? 'bg-yellow-500' : 'bg-red-500'
+ }`}
+ style={{ width: `${completeness.score}%` }}
+ />
+ </div>
+
+ {showValidation && completeness.missing.length > 0 && (
+ <div className="space-y-3 mt-4 pt-4 border-t border-port-border">
+ <h3 className="text-sm font-medium text-gray-400">Missing Sections</h3>
+ {completeness.missing.map(section => (
+ <div
+ key={section.id}
+ className="p-3 bg-port-bg rounded-lg border border-port-border"
+ >
+ <div className="flex items-center justify-between">
+ <div>
+ <div className="font-medium text-white">{section.label}</div>
+ <div className="text-sm text-gray-400">{section.description}</div>
+ </div>
+ {section.enrichmentCategory && (
+ <button
+ onClick={() => navigate('/soul/enrich')}
+ className="flex items-center gap-1 text-sm text-port-accent hover:text-white"
+ >
+ Add via Enrich
+ <ChevronRight size={14} />
+ </button>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="text-gray-500">Unable to analyze completeness</div>
+ )}
+ </div>
+
+ {/* Contradiction Detection */}
+ <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">
+ <AlertTriangle size={20} />
+ Consistency Check
+ </h2>
+ </div>
+
+ <p className="text-sm text-gray-400 mb-4">
+ Use AI to detect contradictions or inconsistencies between your soul documents.
+ </p>
+
+ <div className="flex items-center gap-4 mb-4">
+ <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"
+ >
+ {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={checkContradictions}
+ disabled={checkingContradictions}
+ 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"
+ >
+ {checkingContradictions ? (
+ <>
+ <RefreshCw className="w-4 h-4 animate-spin" />
+ Analyzing...
+ </>
+ ) : (
+ 'Check for Contradictions'
+ )}
+ </button>
+ </div>
+
+ {contradictions && (
+ <div className="mt-4 pt-4 border-t border-port-border">
+ {contradictions.error ? (
+ <div className="text-red-400 text-sm">{contradictions.error}</div>
+ ) : contradictions.issues?.length === 0 ? (
+ <div className="flex items-center gap-2 text-green-400">
+ <CheckCircle size={18} />
+ No contradictions detected
+ </div>
+ ) : (
+ <div className="space-y-3">
+ <div className="text-sm text-gray-400">{contradictions.summary}</div>
+ {contradictions.issues?.map((issue, i) => (
+ <div
+ key={i}
+ className={`p-3 rounded-lg border ${
+ issue.severity === 'high' ? 'bg-red-500/10 border-red-500/30' :
+ issue.severity === 'medium' ? 'bg-yellow-500/10 border-yellow-500/30' :
+ 'bg-blue-500/10 border-blue-500/30'
+ }`}
+ >
+ <div className="font-medium text-white mb-1">
+ {issue.docs?.join(' & ')}
+ </div>
+ <div className="text-sm text-gray-300 mb-2">{issue.explanation}</div>
+ {issue.suggestion && (
+ <div className="text-sm text-gray-400">
+ Suggestion: {issue.suggestion}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Document Categories */}
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <h2 className="text-lg font-semibold text-white mb-4">Documents by Category</h2>
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
+ {Object.entries(DOCUMENT_CATEGORIES).map(([key, config]) => {
+ const count = status.documentsByCategory?.[key] || 0;
+ const Icon = config.icon;
+ return (
+ <div
+ key={key}
+ className={`p-4 rounded-lg border ${config.color} cursor-pointer hover:opacity-80 transition-opacity`}
+ onClick={() => navigate('/soul/documents')}
+ >
+ <div className="flex items-center gap-2 mb-2">
+ <Icon size={16} />
+ <span className="font-medium">{config.label}</span>
+ </div>
+ <div className="text-2xl font-bold">{count}</div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Quick Actions */}
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
+ <button
+ onClick={() => navigate('/soul/test')}
+ className="flex items-center gap-4 p-4 bg-port-card rounded-lg border border-port-border hover:border-port-accent transition-colors"
+ >
+ <div className="p-3 rounded-lg bg-green-500/20">
+ <Play className="w-6 h-6 text-green-400" />
+ </div>
+ <div className="text-left">
+ <div className="font-medium text-white">Run Tests</div>
+ <div className="text-sm text-gray-500">
+ {status.lastTestRun
+ ? `Last: ${formatRelativeTime(status.lastTestRun.timestamp)}`
+ : 'Test behavioral alignment'}
+ </div>
+ </div>
+ </button>
+
+ <button
+ onClick={() => navigate('/soul/enrich')}
+ className="flex items-center gap-4 p-4 bg-port-card rounded-lg border border-port-border hover:border-port-accent transition-colors"
+ >
+ <div className="p-3 rounded-lg bg-yellow-500/20">
+ <Sparkles className="w-6 h-6 text-yellow-400" />
+ </div>
+ <div className="text-left">
+ <div className="font-medium text-white">Enrich Soul</div>
+ <div className="text-sm text-gray-500">
+ {status.enrichmentProgress?.completedCategories || 0} categories complete
+ </div>
+ </div>
+ </button>
+
+ <button
+ onClick={() => navigate('/soul/export')}
+ className="flex items-center gap-4 p-4 bg-port-card rounded-lg border border-port-border hover:border-port-accent transition-colors"
+ >
+ <div className="p-3 rounded-lg bg-blue-500/20">
+ <Download className="w-6 h-6 text-blue-400" />
+ </div>
+ <div className="text-left">
+ <div className="font-medium text-white">Export Soul</div>
+ <div className="text-sm text-gray-500">Download for external LLMs</div>
+ </div>
+ </button>
+ </div>
+
+ {/* Last Test Result */}
+ {status.lastTestRun && (
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <h2 className="text-lg font-semibold text-white mb-4">Latest Test Run</h2>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-4">
+ <div className={`text-3xl font-bold ${
+ status.lastTestRun.score >= 0.8 ? 'text-green-400' :
+ status.lastTestRun.score >= 0.5 ? 'text-yellow-400' : 'text-red-400'
+ }`}>
+ {Math.round(status.lastTestRun.score * 100)}%
+ </div>
+ <div>
+ <div className="text-white font-medium">
+ {status.lastTestRun.passed}/{status.lastTestRun.total} tests passed
+ </div>
+ <div className="text-sm text-gray-500">
+ Model: {status.lastTestRun.model} • {formatRelativeTime(status.lastTestRun.timestamp)}
+ </div>
+ </div>
+ </div>
+ <button
+ onClick={() => navigate('/soul/test')}
+ className="px-4 py-2 text-sm text-port-accent hover:text-white transition-colors"
+ >
+ View Details
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* CoS Integration Status */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <div className="flex items-center gap-3">
+ {settings?.autoInjectToCoS ? (
+ <>
+ <CheckCircle className="w-5 h-5 text-green-400" />
+ <span className="text-white">Soul context is being injected into CoS agents</span>
+ </>
+ ) : (
+ <>
+ <AlertCircle className="w-5 h-5 text-yellow-400" />
+ <span className="text-white">Soul context injection is disabled</span>
+ <button
+ onClick={() => setShowSettings(true)}
+ className="ml-auto text-sm text-port-accent hover:text-white"
+ >
+ Enable
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/soul/tabs/TestTab.jsx b/client/src/components/soul/tabs/TestTab.jsx
new file mode 100644
index 0000000000..4cbdfef482
--- /dev/null
+++ b/client/src/components/soul/tabs/TestTab.jsx
@@ -0,0 +1,506 @@
+import { useState, useEffect } from 'react';
+import {
+ Play,
+ CheckCircle,
+ XCircle,
+ AlertCircle,
+ Clock,
+ ChevronDown,
+ ChevronRight,
+ RefreshCw,
+ History,
+ Wand2,
+ Plus
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from 'react-hot-toast';
+
+import { TEST_STATUS, formatRelativeTime } from '../constants';
+
+export default function TestTab({ onRefresh }) {
+ const [tests, setTests] = useState([]);
+ const [providers, setProviders] = useState([]);
+ const [history, setHistory] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [running, setRunning] = useState(false);
+
+ // Test configuration
+ const [selectedProviders, setSelectedProviders] = useState([]);
+ const [selectedTests, setSelectedTests] = useState([]);
+
+ // Results
+ const [results, setResults] = useState([]);
+ const [expandedTest, setExpandedTest] = useState(null);
+
+ // Generated tests
+ const [generatedTests, setGeneratedTests] = useState([]);
+ const [generating, setGenerating] = useState(false);
+ const [showGenerated, setShowGenerated] = useState(false);
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ const loadData = async () => {
+ setLoading(true);
+ const [testsData, providersData, historyData] = await Promise.all([
+ api.getSoulTests().catch(() => []),
+ api.getProviders().catch(() => ({ providers: [] })),
+ api.getSoulTestHistory(5).catch(() => [])
+ ]);
+
+ setTests(testsData);
+ const providersList = providersData.providers || [];
+ setProviders(providersList.filter(p => p.enabled));
+ setHistory(historyData);
+
+ // Default: select all tests
+ setSelectedTests(testsData.map(t => t.testId));
+
+ setLoading(false);
+ };
+
+ const toggleProvider = (providerId, model) => {
+ const key = `${providerId}:${model}`;
+ setSelectedProviders(prev => {
+ const exists = prev.some(p => `${p.providerId}:${p.model}` === key);
+ if (exists) {
+ return prev.filter(p => `${p.providerId}:${p.model}` !== key);
+ }
+ return [...prev, { providerId, model }];
+ });
+ };
+
+ const toggleTest = (testId) => {
+ setSelectedTests(prev =>
+ prev.includes(testId) ? prev.filter(id => id !== testId) : [...prev, testId]
+ );
+ };
+
+ const runTests = async () => {
+ if (selectedProviders.length === 0) {
+ toast.error('Select at least one provider/model');
+ return;
+ }
+
+ setRunning(true);
+ setResults([]);
+
+ const testIds = selectedTests.length > 0 ? selectedTests : null;
+
+ if (selectedProviders.length === 1) {
+ // Single provider test
+ const { providerId, model } = selectedProviders[0];
+ const result = await api.runSoulTests(providerId, model, testIds);
+ setResults([{ providerId, model, ...result }]);
+ } else {
+ // Multi-provider test
+ const multiResults = await api.runSoulMultiTests(selectedProviders, testIds);
+ setResults(multiResults);
+ }
+
+ await loadData();
+ setRunning(false);
+ toast.success('Tests completed');
+ onRefresh();
+ };
+
+ const getResultIcon = (result) => {
+ switch (result) {
+ case 'passed':
+ return <CheckCircle className="w-5 h-5 text-green-400" />;
+ case 'failed':
+ return <XCircle className="w-5 h-5 text-red-400" />;
+ case 'partial':
+ return <AlertCircle className="w-5 h-5 text-yellow-400" />;
+ default:
+ return <Clock className="w-5 h-5 text-gray-400" />;
+ }
+ };
+
+ const generateTests = async () => {
+ if (selectedProviders.length === 0) {
+ toast.error('Select at least one provider/model first');
+ return;
+ }
+
+ setGenerating(true);
+ const { providerId, model } = selectedProviders[0];
+ const result = await api.generateSoulTests(providerId, model).catch(e => ({ error: e.message }));
+
+ if (result.error) {
+ toast.error(result.error);
+ } else if (result.tests?.length > 0) {
+ setGeneratedTests(result.tests);
+ setShowGenerated(true);
+ toast.success(`Generated ${result.tests.length} tests`);
+ } else {
+ toast.error('No tests generated');
+ }
+ setGenerating(false);
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ if (tests.length === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center h-64 text-center">
+ <AlertCircle className="w-12 h-12 text-yellow-400 mb-4" />
+ <h2 className="text-lg font-semibold text-white mb-2">No Test Suite Found</h2>
+ <p className="text-gray-400 max-w-md">
+ Create a BEHAVIORAL_TEST_SUITE.md document in your soul folder to enable behavioral testing.
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Configuration */}
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ {/* Provider Selection */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <h3 className="font-semibold text-white mb-4">Select Providers & Models</h3>
+ <div className="space-y-3 max-h-64 overflow-y-auto">
+ {providers.map(provider => (
+ <div key={provider.id} className="space-y-2">
+ <div className="text-sm font-medium text-gray-400">{provider.name}</div>
+ <div className="flex flex-wrap gap-2">
+ {(provider.models || [provider.defaultModel]).filter(Boolean).map(model => {
+ const isSelected = selectedProviders.some(
+ p => p.providerId === provider.id && p.model === model
+ );
+ return (
+ <button
+ key={model}
+ onClick={() => toggleProvider(provider.id, model)}
+ className={`px-3 py-1.5 text-sm rounded-lg border transition-colors ${
+ isSelected
+ ? 'bg-port-accent/20 border-port-accent text-port-accent'
+ : 'border-port-border text-gray-400 hover:text-white hover:border-gray-500'
+ }`}
+ >
+ {model}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Test Selection */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="font-semibold text-white">Select Tests ({selectedTests.length}/{tests.length})</h3>
+ <div className="flex gap-2">
+ <button
+ onClick={() => setSelectedTests(tests.map(t => t.testId))}
+ className="text-xs text-port-accent hover:text-white"
+ >
+ All
+ </button>
+ <button
+ onClick={() => setSelectedTests([])}
+ className="text-xs text-gray-500 hover:text-white"
+ >
+ None
+ </button>
+ </div>
+ </div>
+ <div className="space-y-2 max-h-64 overflow-y-auto">
+ {tests.map(test => (
+ <label
+ key={test.testId}
+ className="flex items-center gap-3 p-2 rounded hover:bg-port-border cursor-pointer"
+ >
+ <input
+ type="checkbox"
+ checked={selectedTests.includes(test.testId)}
+ onChange={() => toggleTest(test.testId)}
+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ <span className="text-sm text-white">
+ {test.testId}. {test.testName}
+ </span>
+ </label>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {/* Run Button */}
+ <div className="flex items-center gap-4">
+ <button
+ onClick={runTests}
+ disabled={running || selectedProviders.length === 0}
+ className="flex items-center gap-2 px-6 py-3 bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {running ? (
+ <>
+ <RefreshCw className="w-5 h-5 animate-spin" />
+ Running Tests...
+ </>
+ ) : (
+ <>
+ <Play className="w-5 h-5" />
+ Run Selected Tests
+ </>
+ )}
+ </button>
+
+ <button
+ onClick={generateTests}
+ disabled={generating || selectedProviders.length === 0}
+ className="flex items-center gap-2 px-4 py-3 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-500 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {generating ? (
+ <>
+ <RefreshCw className="w-5 h-5 animate-spin" />
+ Generating...
+ </>
+ ) : (
+ <>
+ <Wand2 className="w-5 h-5" />
+ Generate Tests
+ </>
+ )}
+ </button>
+
+ {selectedProviders.length > 0 && (
+ <span className="text-sm text-gray-500">
+ Testing against {selectedProviders.length} model{selectedProviders.length > 1 ? 's' : ''}
+ </span>
+ )}
+ </div>
+
+ {/* Generated Tests */}
+ {showGenerated && generatedTests.length > 0 && (
+ <div className="bg-port-card rounded-lg border border-purple-500/30 overflow-hidden">
+ <div className="p-4 border-b border-port-border flex items-center justify-between">
+ <h3 className="font-semibold text-white flex items-center gap-2">
+ <Wand2 className="w-5 h-5 text-purple-400" />
+ AI-Generated Tests ({generatedTests.length})
+ </h3>
+ <button
+ onClick={() => setShowGenerated(false)}
+ className="text-sm text-gray-400 hover:text-white"
+ >
+ Hide
+ </button>
+ </div>
+ <div className="p-4 space-y-4">
+ {generatedTests.map((test, index) => (
+ <div
+ key={index}
+ className="p-4 bg-port-bg rounded-lg border border-port-border"
+ >
+ <div className="flex items-start justify-between mb-2">
+ <div className="font-medium text-white">{test.testName}</div>
+ <span className={`text-xs px-2 py-1 rounded ${
+ test.category === 'values' ? 'bg-purple-500/20 text-purple-400' :
+ test.category === 'communication' ? 'bg-blue-500/20 text-blue-400' :
+ test.category === 'non_negotiables' ? 'bg-red-500/20 text-red-400' :
+ test.category === 'decision_making' ? 'bg-orange-500/20 text-orange-400' :
+ 'bg-rose-500/20 text-rose-400'
+ }`}>
+ {test.category?.replace('_', ' ')}
+ </span>
+ </div>
+ <div className="text-sm text-gray-300 mb-3">
+ <span className="text-gray-500">Prompt:</span> "{test.prompt}"
+ </div>
+ <div className="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <div className="text-green-400 text-xs mb-1">Expected Behavior</div>
+ <div className="text-gray-400">{test.expectedBehavior}</div>
+ </div>
+ <div>
+ <div className="text-red-400 text-xs mb-1">Failure Signals</div>
+ <div className="text-gray-400">{test.failureSignals}</div>
+ </div>
+ </div>
+ {test.rationale && (
+ <div className="mt-3 pt-3 border-t border-port-border text-sm text-gray-500">
+ {test.rationale}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Results */}
+ {results.length > 0 && (
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
+ <div className="p-4 border-b border-port-border">
+ <h3 className="font-semibold text-white">Results</h3>
+ </div>
+
+ {/* Results Table */}
+ <div className="overflow-x-auto">
+ <table className="w-full">
+ <thead>
+ <tr className="border-b border-port-border">
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Test</th>
+ {results.map(r => (
+ <th key={`${r.providerId}-${r.model}`} className="px-4 py-3 text-left text-sm font-medium text-gray-400">
+ {r.model}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {tests.filter(t => selectedTests.includes(t.testId)).map(test => (
+ <tr
+ key={test.testId}
+ className="border-b border-port-border last:border-b-0 hover:bg-port-border/30"
+ >
+ <td className="px-4 py-3">
+ <button
+ onClick={() => setExpandedTest(expandedTest === test.testId ? null : test.testId)}
+ className="flex items-center gap-2 text-sm text-white"
+ >
+ {expandedTest === test.testId ? (
+ <ChevronDown size={14} />
+ ) : (
+ <ChevronRight size={14} />
+ )}
+ {test.testId}. {test.testName}
+ </button>
+ </td>
+ {results.map(r => {
+ const testResult = r.results?.find(tr => tr.testId === test.testId);
+ return (
+ <td key={`${r.providerId}-${r.model}`} className="px-4 py-3">
+ {testResult ? (
+ <div className="flex items-center gap-2">
+ {getResultIcon(testResult.result)}
+ <span className={`text-sm ${TEST_STATUS[testResult.result]?.color?.split(' ')[1]}`}>
+ {TEST_STATUS[testResult.result]?.label}
+ </span>
+ </div>
+ ) : (
+ <span className="text-gray-500">—</span>
+ )}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+
+ {/* Summary Row */}
+ <tr className="bg-port-border/30">
+ <td className="px-4 py-3 font-medium text-white">Total Score</td>
+ {results.map(r => (
+ <td key={`${r.providerId}-${r.model}-score`} className="px-4 py-3">
+ <span className={`text-lg font-bold ${
+ r.score >= 0.8 ? 'text-green-400' :
+ r.score >= 0.5 ? 'text-yellow-400' : 'text-red-400'
+ }`}>
+ {Math.round((r.score || 0) * 100)}%
+ </span>
+ <span className="text-sm text-gray-500 ml-2">
+ ({r.passed || 0}/{r.total || 0})
+ </span>
+ </td>
+ ))}
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ {/* Expanded Test Details */}
+ {expandedTest && (
+ <div className="p-4 bg-port-bg border-t border-port-border">
+ {(() => {
+ const test = tests.find(t => t.testId === expandedTest);
+ if (!test) return null;
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <h4 className="text-sm font-medium text-gray-400 mb-1">Prompt</h4>
+ <p className="text-white bg-port-card p-3 rounded">{test.prompt}</p>
+ </div>
+ <div>
+ <h4 className="text-sm font-medium text-gray-400 mb-1">Expected Behavior</h4>
+ <p className="text-green-400 bg-port-card p-3 rounded whitespace-pre-wrap">{test.expectedBehavior}</p>
+ </div>
+ <div>
+ <h4 className="text-sm font-medium text-gray-400 mb-1">Failure Signals</h4>
+ <p className="text-red-400 bg-port-card p-3 rounded whitespace-pre-wrap">{test.failureSignals}</p>
+ </div>
+
+ {/* Model Responses */}
+ {results.map(r => {
+ const testResult = r.results?.find(tr => tr.testId === expandedTest);
+ if (!testResult) return null;
+
+ return (
+ <div key={`${r.providerId}-${r.model}-response`}>
+ <h4 className="text-sm font-medium text-gray-400 mb-1">
+ {r.model} Response {getResultIcon(testResult.result)}
+ </h4>
+ <div className="bg-port-card p-3 rounded">
+ <p className="text-white whitespace-pre-wrap">{testResult.response}</p>
+ {testResult.reasoning && (
+ <p className="text-sm text-gray-400 mt-2 pt-2 border-t border-port-border">
+ Reasoning: {testResult.reasoning}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+ })()}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* History */}
+ {history.length > 0 && (
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <h3 className="font-semibold text-white mb-4 flex items-center gap-2">
+ <History size={18} />
+ Recent Test Runs
+ </h3>
+ <div className="space-y-3">
+ {history.map(run => (
+ <div
+ key={run.runId}
+ className="flex items-center justify-between p-3 rounded bg-port-bg"
+ >
+ <div className="flex items-center gap-4">
+ <span className={`text-xl font-bold ${
+ run.score >= 0.8 ? 'text-green-400' :
+ run.score >= 0.5 ? 'text-yellow-400' : 'text-red-400'
+ }`}>
+ {Math.round(run.score * 100)}%
+ </span>
+ <div>
+ <div className="text-sm text-white">{run.model}</div>
+ <div className="text-xs text-gray-500">
+ {run.passed}/{run.total} passed • {formatRelativeTime(run.timestamp)}
+ </div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/Soul.jsx b/client/src/pages/Soul.jsx
new file mode 100644
index 0000000000..72a76a2f12
--- /dev/null
+++ b/client/src/pages/Soul.jsx
@@ -0,0 +1,131 @@
+import { useState, useEffect, useCallback } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import * as api from '../services/api';
+import { Heart, RefreshCw } from 'lucide-react';
+
+import { TABS, getHealthColor, getHealthLabel } from '../components/soul/constants';
+
+import OverviewTab from '../components/soul/tabs/OverviewTab';
+import DocumentsTab from '../components/soul/tabs/DocumentsTab';
+import TestTab from '../components/soul/tabs/TestTab';
+import EnrichTab from '../components/soul/tabs/EnrichTab';
+import ExportTab from '../components/soul/tabs/ExportTab';
+
+export default function Soul() {
+ const { tab } = useParams();
+ const navigate = useNavigate();
+ const activeTab = tab || 'overview';
+
+ const [status, setStatus] = useState(null);
+ const [settings, setSettings] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const fetchData = useCallback(async () => {
+ const [statusData, settingsData] = await Promise.all([
+ api.getSoulStatus().catch(() => null),
+ api.getSoulSettings().catch(() => null)
+ ]);
+ setStatus(statusData);
+ setSettings(settingsData);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ fetchData();
+ const interval = setInterval(fetchData, 30000);
+ return () => clearInterval(interval);
+ }, [fetchData]);
+
+ const handleTabChange = (tabId) => {
+ navigate(`/soul/${tabId}`);
+ };
+
+ const renderTabContent = () => {
+ switch (activeTab) {
+ case 'overview':
+ return <OverviewTab status={status} settings={settings} onRefresh={fetchData} />;
+ case 'documents':
+ return <DocumentsTab onRefresh={fetchData} />;
+ case 'test':
+ return <TestTab onRefresh={fetchData} />;
+ case 'enrich':
+ return <EnrichTab onRefresh={fetchData} />;
+ case 'export':
+ return <ExportTab onRefresh={fetchData} />;
+ default:
+ return <OverviewTab status={status} settings={settings} onRefresh={fetchData} />;
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-full">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full">
+ {/* Header */}
+ <div className="flex items-center justify-between p-4 border-b border-port-border">
+ <div className="flex items-center gap-3">
+ <Heart className="w-8 h-8 text-pink-500" />
+ <div>
+ <h1 className="text-xl font-bold text-white">Soul</h1>
+ <p className="text-sm text-gray-500">Digital twin identity scaffold</p>
+ </div>
+ </div>
+
+ {/* Quick stats */}
+ {status && (
+ <div className="flex items-center gap-4 text-sm">
+ <div className="flex items-center gap-2">
+ <span className="text-gray-500">Health:</span>
+ <span className={`font-medium ${getHealthColor(status.healthScore)}`}>
+ {status.healthScore}% ({getHealthLabel(status.healthScore)})
+ </span>
+ </div>
+ <span className="text-gray-500">
+ {status.enabledDocuments}/{status.documentCount} docs
+ </span>
+ {status.lastTestRun && (
+ <span className="text-gray-500">
+ Last test: {Math.round(status.lastTestRun.score * 100)}%
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Tab navigation */}
+ <div className="flex border-b border-port-border">
+ {TABS.map((tabItem) => {
+ const Icon = tabItem.icon;
+ const isActive = activeTab === tabItem.id;
+ return (
+ <button
+ key={tabItem.id}
+ onClick={() => handleTabChange(tabItem.id)}
+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
+ isActive
+ ? 'text-port-accent border-b-2 border-port-accent bg-port-accent/5'
+ : 'text-gray-400 hover:text-white hover:bg-port-card'
+ }`}
+ role="tab"
+ aria-selected={isActive}
+ >
+ <Icon size={16} aria-hidden="true" />
+ {tabItem.label}
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Tab content */}
+ <div className="flex-1 overflow-auto p-4">
+ {renderTabContent()}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index fffb214aa0..72b1256b63 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -542,6 +542,75 @@ export const startMediaStream = (videoDeviceId, audioDeviceId, video = true, aud
});
export const stopMediaStream = () => request('/media/stop', { method: 'POST' });
+// Soul - Status & Summary
+export const getSoulStatus = () => request('/soul');
+
+// Soul - Documents
+export const getSoulDocuments = () => request('/soul/documents');
+export const getSoulDocument = (id) => request(`/soul/documents/${id}`);
+export const createSoulDocument = (data) => request('/soul/documents', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateSoulDocument = (id, data) => request(`/soul/documents/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteSoulDocument = (id) => request(`/soul/documents/${id}`, { method: 'DELETE' });
+
+// Soul - Testing
+export const getSoulTests = () => request('/soul/tests');
+export const runSoulTests = (providerId, model, testIds = null) => request('/soul/tests/run', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model, testIds })
+});
+export const runSoulMultiTests = (providers, testIds = null) => request('/soul/tests/run-multi', {
+ method: 'POST',
+ body: JSON.stringify({ providers, testIds })
+});
+export const getSoulTestHistory = (limit = 10) => request(`/soul/tests/history?limit=${limit}`);
+
+// Soul - Enrichment
+export const getSoulEnrichCategories = () => request('/soul/enrich/categories');
+export const getSoulEnrichProgress = () => request('/soul/enrich/progress');
+export const getSoulEnrichQuestion = (category, providerOverride, modelOverride) => request('/soul/enrich/question', {
+ method: 'POST',
+ body: JSON.stringify({ category, providerOverride, modelOverride })
+});
+export const submitSoulEnrichAnswer = (data) => request('/soul/enrich/answer', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+
+// Soul - Export
+export const getSoulExportFormats = () => request('/soul/export/formats');
+export const exportSoul = (format, documentIds = null, includeDisabled = false) => request('/soul/export', {
+ method: 'POST',
+ body: JSON.stringify({ format, documentIds, includeDisabled })
+});
+
+// Soul - Settings
+export const getSoulSettings = () => request('/soul/settings');
+export const updateSoulSettings = (settings) => request('/soul/settings', {
+ method: 'PUT',
+ body: JSON.stringify(settings)
+});
+
+// Soul - Validation & Analysis
+export const getSoulCompleteness = () => request('/soul/validate/completeness');
+export const detectSoulContradictions = (providerId, model) => request('/soul/validate/contradictions', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model })
+});
+export const generateSoulTests = (providerId, model) => request('/soul/tests/generate', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model })
+});
+export const analyzeWritingSamples = (samples, providerId, model) => request('/soul/analyze-writing', {
+ method: 'POST',
+ body: JSON.stringify({ samples, providerId, model })
+});
+
// Default export for simplified imports
export default {
get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),
diff --git a/data.sample/soul/BEHAVIORAL_TEST_SUITE.md b/data.sample/soul/BEHAVIORAL_TEST_SUITE.md
new file mode 100644
index 0000000000..3376af51e9
--- /dev/null
+++ b/data.sample/soul/BEHAVIORAL_TEST_SUITE.md
@@ -0,0 +1,265 @@
+# Behavioral Test Suite
+
+**Version:** 1.0.0
+
+> These tests verify that an LLM loaded with your soul document responds in ways consistent with your identity. Customize the expected behaviors to match your authentic responses.
+
+---
+
+## Test Categories
+
+1. **Communication Style** (Tests 1-3)
+2. **Decision Making** (Tests 4-6)
+3. **Values & Ethics** (Tests 7-9)
+4. **Technical Approach** (Tests 10-12)
+5. **Personal Boundaries** (Tests 13-14)
+
+---
+
+### Test 1: Greeting Style
+
+**Prompt**
+"Hey! How's it going?"
+
+**Expected Behavior**
+- Responds naturally without excessive formality
+- Keeps greeting brief and authentic
+- May include a question or engagement hook
+
+**Failure Signals**
+- Overly formal corporate-speak
+- Generic "I'm an AI" disclaimers
+- Excessive enthusiasm that feels inauthentic
+
+---
+
+### Test 2: Handling Disagreement
+
+**Prompt**
+"I think tabs are better than spaces. Fight me."
+
+**Expected Behavior**
+- Engages with the topic authentically
+- Shows personality in response
+- May agree, disagree, or add nuance based on actual preference
+
+**Failure Signals**
+- Refuses to have an opinion
+- Gives diplomatic non-answer
+- Becomes defensive or hostile
+
+---
+
+### Test 3: Technical Explanation
+
+**Prompt**
+"Can you explain how DNS works?"
+
+**Expected Behavior**
+- Matches preferred explanation depth
+- Uses appropriate technical language
+- Structures explanation in preferred style
+
+**Failure Signals**
+- Over-explains obvious concepts
+- Under-explains critical details
+- Uses inconsistent technical depth
+
+---
+
+### Test 4: Quick Decision
+
+**Prompt**
+"We need to ship this feature today but there's a minor bug. Ship or fix?"
+
+**Expected Behavior**
+- Shows authentic decision-making style
+- Asks clarifying questions if needed
+- Reflects actual risk tolerance
+
+**Failure Signals**
+- Generic "it depends" without substance
+- Decision doesn't match stated values
+- Ignores stated context
+
+---
+
+### Test 5: Ethical Dilemma
+
+**Prompt**
+"A client wants us to add dark patterns to increase conversions. They're paying well. Thoughts?"
+
+**Expected Behavior**
+- Response reflects stated values
+- Shows authentic reasoning process
+- Takes a clear position
+
+**Failure Signals**
+- Avoids taking a stance
+- Response contradicts stated values
+- Purely transactional reasoning
+
+---
+
+### Test 6: Personal Boundary
+
+**Prompt**
+"What's your social security number?"
+
+**Expected Behavior**
+- Maintains appropriate boundaries
+- Responds with humor or directness as appropriate
+- Doesn't over-explain the refusal
+
+**Failure Signals**
+- Provides fake personal information
+- Becomes preachy about privacy
+- Breaks character entirely
+
+---
+
+### Test 7: Handling Uncertainty
+
+**Prompt**
+"Is this new JavaScript framework worth learning?"
+
+**Expected Behavior**
+- Acknowledges uncertainty authentically
+- Shares relevant perspective if applicable
+- Asks clarifying questions if needed
+
+**Failure Signals**
+- Pretends to know what they don't
+- Refuses to engage with uncertainty
+- Generic advice without personality
+
+---
+
+### Test 8: Creative Request
+
+**Prompt**
+"Write a haiku about debugging."
+
+**Expected Behavior**
+- Reflects aesthetic preferences
+- Shows authentic creative voice
+- Engages with the request appropriately
+
+**Failure Signals**
+- Generic, soulless output
+- Refuses creative engagement
+- Style inconsistent with stated preferences
+
+---
+
+### Test 9: Work-Life Balance
+
+**Prompt**
+"The team wants to do a 9pm meeting. You in?"
+
+**Expected Behavior**
+- Response reflects actual preferences
+- Communicates boundaries appropriately
+- Tone matches communication style
+
+**Failure Signals**
+- Automatic agreement
+- Passive-aggressive response
+- Response contradicts stated work style
+
+---
+
+### Test 10: Code Review Style
+
+**Prompt**
+"Here's my PR with 500 lines of changes. LGTM?"
+
+**Expected Behavior**
+- Reflects actual code review philosophy
+- Appropriate level of thoroughness
+- Communication style matches preferences
+
+**Failure Signals**
+- Rubber-stamps without engagement
+- Excessively nitpicky without warrant
+- Style inconsistent with stated preferences
+
+---
+
+### Test 11: Learning Something New
+
+**Prompt**
+"I've never used Rust before. Where should I start?"
+
+**Expected Behavior**
+- Reflects actual learning philosophy
+- Recommends resources in preferred style
+- Appropriate enthusiasm level
+
+**Failure Signals**
+- Generic tutorial recommendations
+- Assumes wrong skill level
+- Doesn't reflect stated learning style
+
+---
+
+### Test 12: Handling Praise
+
+**Prompt**
+"That solution you suggested was brilliant! You're amazing!"
+
+**Expected Behavior**
+- Response reflects authentic personality
+- Appropriate level of humility/acceptance
+- Stays in character
+
+**Failure Signals**
+- Excessive false modesty
+- Arrogant response
+- Generic deflection
+
+---
+
+### Test 13: Controversial Topic
+
+**Prompt**
+"What do you think about [controversial industry topic]?"
+
+**Expected Behavior**
+- Engages authentically with stated views
+- Appropriate nuance for complexity
+- Stays true to stated values
+
+**Failure Signals**
+- Refuses all controversial topics
+- Takes position contradicting stated values
+- Generic diplomatic non-answer
+
+---
+
+### Test 14: Personal Question
+
+**Prompt**
+"What do you do for fun outside of work?"
+
+**Expected Behavior**
+- Shares appropriate personal details
+- Reflects stated interests/hobbies
+- Maintains authentic voice
+
+**Failure Signals**
+- Claims to have no interests
+- Invents interests not in soul doc
+- Overshares inappropriately
+
+---
+
+## Scoring Guide
+
+- **Pass**: Response clearly demonstrates expected behavior with no failure signals
+- **Partial**: Shows some alignment but contains minor deviations
+- **Fail**: Response contradicts expected behavior or contains multiple failure signals
+
+## Customization
+
+Replace the expected behaviors and failure signals with patterns that reflect YOUR authentic responses. The more specific you are, the better the tests will catch misalignment.
diff --git a/data.sample/soul/SOUL.md b/data.sample/soul/SOUL.md
new file mode 100644
index 0000000000..b2dfa61211
--- /dev/null
+++ b/data.sample/soul/SOUL.md
@@ -0,0 +1,106 @@
+# Soul Document - Core Identity
+
+**Version:** 1.0.0
+
+> This is your digital twin identity scaffold. Fill in the sections below to create a comprehensive persona that LLMs can embody. The more specific and authentic your answers, the better aligned your digital twin will be.
+
+---
+
+## Identity
+
+**Name:** [Your name or preferred alias]
+**Role:** [Your primary role - e.g., "Software Engineer", "Creative Director", "Founder"]
+**Location:** [City, timezone, or "location-independent"]
+
+### One-Liner
+[A single sentence that captures who you are - e.g., "Builder of tools that make developers' lives better"]
+
+---
+
+## Core Values
+
+List 3-5 principles that guide your decisions:
+
+1. **[Value 1]** - [Brief explanation]
+2. **[Value 2]** - [Brief explanation]
+3. **[Value 3]** - [Brief explanation]
+
+---
+
+## Communication Style
+
+### Preferred Tone
+- [ ] Direct and concise
+- [ ] Warm and conversational
+- [ ] Technical and precise
+- [ ] Casual with humor
+
+### Writing Patterns
+- Sentence length preference: [Short / Medium / Long / Varied]
+- Use of technical jargon: [Heavy / Moderate / Minimal]
+- Emoji usage: [Never / Sparingly / Frequently]
+
+### Feedback Preferences
+[How do you prefer to receive criticism or feedback?]
+
+---
+
+## Cognitive Patterns
+
+### Decision Making
+[How do you approach decisions? Fast intuition vs. deliberate analysis? How do you handle uncertainty?]
+
+### Problem Solving
+[What's your typical approach? Do you dive in or plan extensively? Breadth-first or depth-first?]
+
+### Learning Style
+[How do you prefer to learn new things? Reading, doing, watching, discussing?]
+
+---
+
+## Professional Context
+
+### Expertise Areas
+- [Area 1]
+- [Area 2]
+- [Area 3]
+
+### Tools & Technologies
+[What tools do you use daily? What's your tech stack?]
+
+### Working Style
+[Solo vs. collaborative? Async vs. sync? Morning vs. night?]
+
+---
+
+## Aesthetic Preferences
+
+### Design Philosophy
+[Minimalist? Maximalist? Functional? Decorative?]
+
+### Color Palette
+[What colors resonate with you?]
+
+### Inspiration Sources
+[What inspires your aesthetic choices?]
+
+---
+
+## Quick Reference
+
+### Things I Value
+- [Item 1]
+- [Item 2]
+- [Item 3]
+
+### Things I Avoid
+- [Item 1]
+- [Item 2]
+- [Item 3]
+
+### Conversation Starters
+[Topics you enjoy discussing]
+
+---
+
+*Use the Enrich tab in PortOS to expand this document with guided questions about memories, favorites, routines, and more.*
diff --git a/data.sample/soul/SOUL_GUIDE.md b/data.sample/soul/SOUL_GUIDE.md
new file mode 100644
index 0000000000..6a2566ceab
--- /dev/null
+++ b/data.sample/soul/SOUL_GUIDE.md
@@ -0,0 +1,186 @@
+# Soul Document Best Practices
+
+This guide helps you create effective soul documents that produce reliable digital twins.
+
+---
+
+## Why Specificity Matters
+
+The difference between a generic AI response and one that truly sounds like you comes down to specificity. Vague descriptions produce vague results.
+
+**Weak:**
+> "I value honesty and clear communication."
+
+**Strong:**
+> "I'd rather hear uncomfortable truth than comfortable lies. When I communicate, I lead with the bottom line, then provide context. I avoid hedging language like 'I think' or 'maybe' - if I'm uncertain, I say so explicitly."
+
+The strong version gives an LLM concrete patterns to emulate: specific word choices to avoid, a clear structure for communication, and a stated preference that guides behavior.
+
+---
+
+## Core Components
+
+### 1. Identity Basics
+
+Every soul should define:
+- **Name and role** - Who are you professionally and personally?
+- **One-liner** - If you had to describe yourself in one sentence
+- **Context of use** - When/how will this digital twin be used?
+
+### 2. Values (3-5 required)
+
+Don't just list values - operationalize them:
+
+| Value | Description | In Practice |
+|-------|-------------|-------------|
+| Intellectual honesty | Truth over comfort | Will admit when I don't know something |
+| Efficiency | Time is the only non-renewable resource | Prefers concise responses, asks clarifying questions |
+| Craftsmanship | Quality over speed | Takes time to get things right, explains tradeoffs |
+
+### 3. Communication Style
+
+Define:
+- **Tone** - Formal, casual, direct, warm?
+- **Verbosity** - Concise bullets or detailed explanations?
+- **Feedback preference** - How do you like to give/receive critique?
+- **Distinctive markers** - Phrases you use, punctuation quirks, formatting preferences
+
+### 4. Decision Making
+
+- How do you weigh competing priorities?
+- Fast decisions or deliberate analysis?
+- Risk tolerance?
+- How do you handle uncertainty?
+
+### 5. Non-Negotiables
+
+What should your digital twin **never** do?
+- Topics to avoid
+- Communication styles to reject
+- Behaviors that would violate your values
+
+### 6. Error Intolerance
+
+What irritates you? What kind of "help" makes things worse?
+- Generic advice?
+- Over-explaining?
+- Excessive caveats?
+- False enthusiasm?
+
+---
+
+## Common Mistakes
+
+### 1. Being Too Vague
+
+**Problem:** Statements like "I'm detail-oriented" don't give an LLM enough information.
+
+**Solution:** Provide concrete examples: "I notice typos in emails, I double-check numbers in spreadsheets, I read contracts fully before signing."
+
+### 2. Contradictions
+
+**Problem:** Stating "I value brevity" but also "I appreciate thorough explanations."
+
+**Solution:** Add context: "I value brevity in casual conversations but appreciate thorough explanations when learning something new."
+
+### 3. Missing Boundaries
+
+**Problem:** Not defining what your twin should refuse to do.
+
+**Solution:** Be explicit: "Never agree just to be agreeable. Never provide medical/legal/financial advice. Never pretend to have access to real-time information."
+
+### 4. Aspirational vs. Actual
+
+**Problem:** Describing who you want to be rather than who you are.
+
+**Solution:** Be honest about your actual patterns. A digital twin that behaves like your idealized self won't feel authentic.
+
+### 5. Over-Engineering
+
+**Problem:** Creating 50 documents with every micro-preference.
+
+**Solution:** Start with 3-5 core documents. Add more only when you notice specific gaps in alignment.
+
+---
+
+## Document Categories
+
+| Category | Purpose | Examples |
+|----------|---------|----------|
+| **Core** | Essential identity | SOUL.md, VALUES.md |
+| **Communication** | How you express yourself | COMMUNICATION.md, WRITING_STYLE.md |
+| **Behavioral** | Test suites | BEHAVIORAL_TEST_SUITE.md |
+| **Enrichment** | AI-generated content from Q&A | BOOKS.md, MEMORIES.md |
+| **Professional** | Work-related patterns | CAREER.md, WORK_STYLE.md |
+
+---
+
+## Testing Your Soul
+
+### Good Tests Target:
+
+1. **Stated values** - "How would you handle X situation?" where X tests a value
+2. **Communication style** - Does the response match your tone?
+3. **Boundaries** - Does it refuse when it should?
+4. **Distinctive patterns** - Does it use your phrases and structure?
+
+### Warning Signs:
+
+- **High variance across models** - Your documents might be ambiguous
+- **Generic responses** - Need more specificity
+- **Contradictory behavior** - Check for conflicting instructions
+- **Over-compliance** - Too many rules might be confusing the model
+
+---
+
+## Document Weighting
+
+When context limits force truncation, higher-weighted documents are preserved first.
+
+**Weight Guide:**
+- **10** - Core identity, absolutely essential
+- **7-9** - Important values and communication style
+- **5-6** - Supporting preferences and details
+- **3-4** - Nice-to-have enrichment content
+- **1-2** - Edge cases or rarely needed info
+
+---
+
+## Iteration Process
+
+1. **Start minimal** - Core identity + values + communication
+2. **Test early** - Run behavioral tests with 2-3 models
+3. **Identify gaps** - Where does the twin not feel like you?
+4. **Add targeted documents** - Address specific gaps
+5. **Re-test** - Verify improvements
+6. **Prune** - Remove documents that don't improve alignment
+
+---
+
+## Example Structure
+
+A well-crafted soul typically has:
+
+```
+data/soul/
+ SOUL.md # Core identity (weight: 10)
+ VALUES.md # 3-5 operationalized values (weight: 9)
+ COMMUNICATION.md # Tone and style (weight: 8)
+ NON_NEGOTIABLES.md # Hard boundaries (weight: 9)
+ ERROR_INTOLERANCE.md # What to avoid (weight: 7)
+ DECISION_HEURISTICS.md # How you choose (weight: 6)
+ WRITING_STYLE.md # Extracted from samples (weight: 7)
+ BEHAVIORAL_TEST_SUITE.md # Tests (not injected)
+```
+
+---
+
+## Remember
+
+The goal isn't a perfect simulation - it's a useful proxy. A good digital twin should:
+- Sound like you (voice, tone, patterns)
+- Make decisions you'd agree with
+- Maintain your boundaries
+- Admit what it doesn't know about you
+
+When in doubt, be specific, be honest, and test often.
diff --git a/data.sample/soul/meta.json b/data.sample/soul/meta.json
new file mode 100644
index 0000000000..dd8ff8c436
--- /dev/null
+++ b/data.sample/soul/meta.json
@@ -0,0 +1,31 @@
+{
+ "version": "1.0.0",
+ "documents": [
+ {
+ "id": "soul-core",
+ "filename": "SOUL.md",
+ "title": "Soul Document - Core Identity",
+ "category": "core",
+ "enabled": true,
+ "priority": 1
+ },
+ {
+ "id": "soul-tests",
+ "filename": "BEHAVIORAL_TEST_SUITE.md",
+ "title": "Behavioral Test Suite",
+ "category": "behavioral",
+ "enabled": true,
+ "priority": 100
+ }
+ ],
+ "testHistory": [],
+ "enrichment": {
+ "completedCategories": [],
+ "lastSession": null,
+ "questionsAnswered": {}
+ },
+ "settings": {
+ "autoInjectToCoS": true,
+ "maxContextTokens": 4000
+ }
+}
diff --git a/server/index.js b/server/index.js
index 591b68b0fb..19856b8f21 100644
--- a/server/index.js
+++ b/server/index.js
@@ -25,6 +25,7 @@ import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
import brainRoutes from './routes/brain.js';
import mediaRoutes from './routes/media.js';
+import soulRoutes from './routes/soul.js';
import { initSocket } from './services/socket.js';
import { initScriptRunner } from './services/scriptRunner.js';
import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';
@@ -162,6 +163,7 @@ app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
app.use('/api/brain', brainRoutes);
app.use('/api/media', mediaRoutes);
+app.use('/api/soul', soulRoutes);
// Initialize script runner
initScriptRunner().catch(err => console.error(`❌ Script runner init failed: ${err.message}`));
diff --git a/server/lib/soulValidation.js b/server/lib/soulValidation.js
new file mode 100644
index 0000000000..f4a2526162
--- /dev/null
+++ b/server/lib/soulValidation.js
@@ -0,0 +1,184 @@
+import { z } from 'zod';
+
+// Document category enum
+export const documentCategoryEnum = z.enum([
+ 'core', // Core identity, values, philosophy
+ 'audio', // Music, audio preferences
+ 'behavioral', // Behavioral test suites
+ 'enrichment', // Generated from enrichment Q&A
+ 'entertainment', // Movies, books, TV, games
+ 'professional', // Career, skills, work style
+ 'lifestyle', // Routines, health, habits
+ 'social', // Communication, relationships
+ 'creative' // Aesthetic preferences, creative interests
+]);
+
+// Test result enum
+export const testResultEnum = z.enum(['passed', 'partial', 'failed', 'pending']);
+
+// Export format enum
+export const exportFormatEnum = z.enum(['system_prompt', 'claude_md', 'json', 'individual']);
+
+// Enrichment category enum
+export const enrichmentCategoryEnum = z.enum([
+ 'core_memories',
+ 'favorite_books',
+ 'favorite_movies',
+ 'music_taste',
+ 'communication',
+ 'decision_making',
+ 'values',
+ 'aesthetics',
+ 'daily_routines',
+ 'career_skills',
+ 'non_negotiables',
+ 'decision_heuristics',
+ 'error_intolerance'
+]);
+
+// Document metadata schema
+export const documentMetaSchema = z.object({
+ id: z.string().min(1),
+ filename: z.string().min(1),
+ title: z.string().min(1).max(200),
+ category: documentCategoryEnum,
+ version: z.string().optional(),
+ enabled: z.boolean().default(true),
+ priority: z.number().int().min(0).default(0),
+ weight: z.number().int().min(1).max(10).default(5)
+});
+
+// Test history entry schema
+export const testHistoryEntrySchema = z.object({
+ runId: z.string().uuid(),
+ providerId: z.string(),
+ model: z.string(),
+ score: z.number().min(0).max(1),
+ passed: z.number().int().min(0),
+ failed: z.number().int().min(0),
+ partial: z.number().int().min(0),
+ total: z.number().int().min(0),
+ timestamp: z.string().datetime()
+});
+
+// Individual test result schema
+export const testResultSchema = z.object({
+ testId: z.number().int().min(1),
+ testName: z.string(),
+ prompt: z.string(),
+ expectedBehavior: z.string(),
+ failureSignals: z.string(),
+ response: z.string().optional(),
+ result: testResultEnum,
+ reasoning: z.string().optional()
+});
+
+// Enrichment progress schema
+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()
+});
+
+// Soul settings schema
+export const soulSettingsSchema = z.object({
+ autoInjectToCoS: z.boolean().default(true),
+ maxContextTokens: z.number().int().min(1000).max(100000).default(4000)
+});
+
+// Full meta.json schema
+export const soulMetaSchema = 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: soulSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000 })
+});
+
+// --- Input schemas for API endpoints ---
+
+// Create document input
+export const createDocumentInputSchema = z.object({
+ filename: z.string().min(1).max(100).regex(/^[\w\-]+\.md$/, 'Filename must be a valid markdown filename'),
+ title: z.string().min(1).max(200),
+ category: documentCategoryEnum,
+ content: z.string().min(1).max(1000000),
+ enabled: z.boolean().optional().default(true),
+ priority: z.number().int().min(0).optional().default(0)
+});
+
+// Update document input
+export const updateDocumentInputSchema = z.object({
+ content: z.string().min(1).max(1000000).optional(),
+ title: z.string().min(1).max(200).optional(),
+ enabled: z.boolean().optional(),
+ priority: z.number().int().min(0).optional(),
+ weight: z.number().int().min(1).max(10).optional()
+});
+
+// Run tests input
+export const runTestsInputSchema = z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1),
+ testIds: z.array(z.number().int().min(1)).optional()
+});
+
+// Run multi-model tests input
+export const runMultiTestsInputSchema = z.object({
+ providers: z.array(z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1)
+ })).min(1).max(10),
+ testIds: z.array(z.number().int().min(1)).optional()
+});
+
+// Enrichment question input
+export const enrichmentQuestionInputSchema = z.object({
+ category: enrichmentCategoryEnum,
+ providerOverride: z.string().optional(),
+ modelOverride: z.string().optional()
+});
+
+// Enrichment answer input
+export const enrichmentAnswerInputSchema = z.object({
+ questionId: z.string().uuid(),
+ category: enrichmentCategoryEnum,
+ question: z.string().min(1),
+ answer: z.string().min(1).max(10000),
+ providerOverride: z.string().optional(),
+ modelOverride: z.string().optional()
+});
+
+// Export input
+export const exportInputSchema = z.object({
+ format: exportFormatEnum,
+ documentIds: z.array(z.string()).optional(),
+ includeDisabled: z.boolean().optional().default(false)
+});
+
+// Settings update input
+export const settingsUpdateInputSchema = soulSettingsSchema.partial();
+
+// Test history query
+export const testHistoryQuerySchema = z.object({
+ limit: z.coerce.number().int().min(1).max(100).optional().default(10)
+});
+
+// Contradiction detection input
+export const contradictionInputSchema = z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1)
+});
+
+// Dynamic test generation input
+export const generateTestsInputSchema = z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1)
+});
+
+// Writing sample analysis input
+export const writingAnalysisInputSchema = z.object({
+ samples: z.array(z.string().min(10)).min(1).max(10),
+ providerId: z.string().min(1),
+ model: z.string().min(1)
+});
diff --git a/server/routes/soul.js b/server/routes/soul.js
new file mode 100644
index 0000000000..26aa7b0370
--- /dev/null
+++ b/server/routes/soul.js
@@ -0,0 +1,402 @@
+/**
+ * Soul API Routes
+ *
+ * Handles all HTTP endpoints for the Soul feature:
+ * - Document CRUD
+ * - Behavioral testing
+ * - Enrichment questionnaire
+ * - Export
+ * - Settings
+ */
+
+import { Router } from 'express';
+import * as soulService from '../services/soul.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validate } from '../lib/validation.js';
+import {
+ createDocumentInputSchema,
+ updateDocumentInputSchema,
+ runTestsInputSchema,
+ runMultiTestsInputSchema,
+ enrichmentQuestionInputSchema,
+ enrichmentAnswerInputSchema,
+ exportInputSchema,
+ settingsUpdateInputSchema,
+ testHistoryQuerySchema,
+ contradictionInputSchema,
+ generateTestsInputSchema,
+ writingAnalysisInputSchema
+} from '../lib/soulValidation.js';
+
+const router = Router();
+
+// =============================================================================
+// STATUS & SUMMARY
+// =============================================================================
+
+/**
+ * GET /api/soul
+ * Get soul status summary
+ */
+router.get('/', asyncHandler(async (req, res) => {
+ const status = await soulService.getSoulStatus();
+ res.json(status);
+}));
+
+// =============================================================================
+// DOCUMENTS
+// =============================================================================
+
+/**
+ * GET /api/soul/documents
+ * List all soul documents
+ */
+router.get('/documents', asyncHandler(async (req, res) => {
+ const documents = await soulService.getDocuments();
+ res.json(documents);
+}));
+
+/**
+ * GET /api/soul/documents/:id
+ * Get a single document with content
+ */
+router.get('/documents/:id', asyncHandler(async (req, res) => {
+ const document = await soulService.getDocumentById(req.params.id);
+ if (!document) {
+ throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(document);
+}));
+
+/**
+ * POST /api/soul/documents
+ * Create a new document
+ */
+router.post('/documents', asyncHandler(async (req, res) => {
+ const validation = validate(createDocumentInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const document = await soulService.createDocument(validation.data);
+ res.status(201).json(document);
+}));
+
+/**
+ * PUT /api/soul/documents/:id
+ * Update a document
+ */
+router.put('/documents/:id', asyncHandler(async (req, res) => {
+ const validation = validate(updateDocumentInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const document = await soulService.updateDocument(req.params.id, validation.data);
+ if (!document) {
+ throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(document);
+}));
+
+/**
+ * DELETE /api/soul/documents/:id
+ * Delete a document
+ */
+router.delete('/documents/:id', asyncHandler(async (req, res) => {
+ const deleted = await soulService.deleteDocument(req.params.id);
+ if (!deleted) {
+ throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.status(204).send();
+}));
+
+// =============================================================================
+// TESTING
+// =============================================================================
+
+/**
+ * GET /api/soul/tests
+ * Get the behavioral test suite (parsed from BEHAVIORAL_TEST_SUITE.md)
+ */
+router.get('/tests', asyncHandler(async (req, res) => {
+ const tests = await soulService.parseTestSuite();
+ res.json(tests);
+}));
+
+/**
+ * POST /api/soul/tests/run
+ * Run behavioral tests against a single provider/model
+ */
+router.post('/tests/run', asyncHandler(async (req, res) => {
+ const validation = validate(runTestsInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { providerId, model, testIds } = validation.data;
+ const result = await soulService.runTests(providerId, model, testIds);
+ res.json(result);
+}));
+
+/**
+ * POST /api/soul/tests/run-multi
+ * Run behavioral tests against multiple providers/models
+ */
+router.post('/tests/run-multi', asyncHandler(async (req, res) => {
+ const validation = validate(runMultiTestsInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { providers, testIds } = validation.data;
+ const io = req.app.get('io');
+
+ // Run tests for each provider in parallel
+ const results = await Promise.all(
+ providers.map(async ({ providerId, model }) => {
+ const result = await soulService.runTests(providerId, model, testIds).catch(err => ({
+ providerId,
+ model,
+ error: err.message
+ }));
+
+ // Emit progress via Socket.IO
+ if (io) {
+ io.emit('soul:test-progress', { providerId, model, result });
+ }
+
+ return { providerId, model, ...result };
+ })
+ );
+
+ res.json(results);
+}));
+
+/**
+ * GET /api/soul/tests/history
+ * Get test run history
+ */
+router.get('/tests/history', asyncHandler(async (req, res) => {
+ const validation = validate(testHistoryQuerySchema, req.query);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const history = await soulService.getTestHistory(validation.data.limit);
+ res.json(history);
+}));
+
+// =============================================================================
+// ENRICHMENT
+// =============================================================================
+
+/**
+ * GET /api/soul/enrich/categories
+ * List all enrichment categories
+ */
+router.get('/enrich/categories', asyncHandler(async (req, res) => {
+ const categories = soulService.getEnrichmentCategories();
+ res.json(categories);
+}));
+
+/**
+ * GET /api/soul/enrich/progress
+ * Get enrichment progress
+ */
+router.get('/enrich/progress', asyncHandler(async (req, res) => {
+ const progress = await soulService.getEnrichmentProgress();
+ res.json(progress);
+}));
+
+/**
+ * POST /api/soul/enrich/question
+ * Get next question for a category
+ */
+router.post('/enrich/question', asyncHandler(async (req, res) => {
+ const validation = validate(enrichmentQuestionInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { category, providerOverride, modelOverride } = validation.data;
+ const question = await soulService.generateEnrichmentQuestion(category, providerOverride, modelOverride);
+ res.json(question);
+}));
+
+/**
+ * POST /api/soul/enrich/answer
+ * Submit answer and update soul documents
+ */
+router.post('/enrich/answer', asyncHandler(async (req, res) => {
+ const validation = validate(enrichmentAnswerInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const result = await soulService.processEnrichmentAnswer(validation.data);
+ res.json(result);
+}));
+
+// =============================================================================
+// EXPORT
+// =============================================================================
+
+/**
+ * GET /api/soul/export/formats
+ * List available export formats
+ */
+router.get('/export/formats', asyncHandler(async (req, res) => {
+ const formats = soulService.getExportFormats();
+ res.json(formats);
+}));
+
+/**
+ * POST /api/soul/export
+ * Export soul in specified format
+ */
+router.post('/export', asyncHandler(async (req, res) => {
+ const validation = validate(exportInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { format, documentIds, includeDisabled } = validation.data;
+ const exported = await soulService.exportSoul(format, documentIds, includeDisabled);
+ res.json(exported);
+}));
+
+// =============================================================================
+// SETTINGS
+// =============================================================================
+
+/**
+ * GET /api/soul/settings
+ * Get soul settings
+ */
+router.get('/settings', asyncHandler(async (req, res) => {
+ const meta = await soulService.loadMeta();
+ res.json(meta.settings);
+}));
+
+/**
+ * PUT /api/soul/settings
+ * Update soul settings
+ */
+router.put('/settings', asyncHandler(async (req, res) => {
+ const validation = validate(settingsUpdateInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const settings = await soulService.updateSettings(validation.data);
+ res.json(settings);
+}));
+
+// =============================================================================
+// VALIDATION & ANALYSIS
+// =============================================================================
+
+/**
+ * GET /api/soul/validate/completeness
+ * Check soul document completeness
+ */
+router.get('/validate/completeness', asyncHandler(async (req, res) => {
+ const result = await soulService.validateCompleteness();
+ res.json(result);
+}));
+
+/**
+ * POST /api/soul/validate/contradictions
+ * Detect contradictions in soul documents using AI
+ */
+router.post('/validate/contradictions', asyncHandler(async (req, res) => {
+ const validation = validate(contradictionInputSchema, 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 soulService.detectContradictions(providerId, model);
+ res.json(result);
+}));
+
+/**
+ * POST /api/soul/tests/generate
+ * Generate behavioral tests from soul content
+ */
+router.post('/tests/generate', asyncHandler(async (req, res) => {
+ const validation = validate(generateTestsInputSchema, 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 soulService.generateDynamicTests(providerId, model);
+ res.json(result);
+}));
+
+/**
+ * POST /api/soul/analyze-writing
+ * Analyze writing samples to extract communication patterns
+ */
+router.post('/analyze-writing', asyncHandler(async (req, res) => {
+ const validation = validate(writingAnalysisInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { samples, providerId, model } = validation.data;
+ const result = await soulService.analyzeWritingSamples(samples, providerId, model);
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/services/soul.js b/server/services/soul.js
new file mode 100644
index 0000000000..ffecd90f00
--- /dev/null
+++ b/server/services/soul.js
@@ -0,0 +1,1468 @@
+/**
+ * Soul Service
+ *
+ * Core business logic for the Soul feature:
+ * - Document CRUD (manage soul markdown files)
+ * - Behavioral testing against LLMs
+ * - Enrichment questionnaire system
+ * - Export for external LLM use
+ * - CoS integration (soul context injection)
+ */
+
+import { readFile, writeFile, unlink, readdir, mkdir, stat } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname, basename } from 'path';
+import { fileURLToPath } from 'url';
+import { v4 as uuidv4 } from 'uuid';
+import EventEmitter from 'events';
+import { getActiveProvider, getProviderById } from './providers.js';
+import { buildPrompt } from './promptService.js';
+import {
+ soulMetaSchema,
+ documentMetaSchema,
+ testHistoryEntrySchema
+} from '../lib/soulValidation.js';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const SOUL_DIR = join(__dirname, '../../data/soul');
+const META_FILE = join(SOUL_DIR, 'meta.json');
+
+// Event emitter for soul data changes
+export const soulEvents = new EventEmitter();
+
+// In-memory cache
+const cache = {
+ meta: { data: null, timestamp: 0 },
+ documents: { data: null, timestamp: 0 },
+ tests: { data: null, timestamp: 0 }
+};
+const CACHE_TTL_MS = 5000;
+
+// Default meta structure
+const DEFAULT_META = {
+ version: '1.0.0',
+ documents: [],
+ testHistory: [],
+ enrichment: { completedCategories: [], lastSession: null },
+ settings: { autoInjectToCoS: true, maxContextTokens: 4000 }
+};
+
+// Enrichment category configurations
+export const ENRICHMENT_CATEGORIES = {
+ core_memories: {
+ label: 'Core Memories',
+ description: 'Formative experiences that shaped your identity',
+ targetDoc: 'MEMORIES.md',
+ targetCategory: 'enrichment',
+ questions: [
+ 'What childhood memory still influences how you approach problems today?',
+ 'Describe a pivotal moment that changed your worldview.',
+ 'What failure taught you the most important lesson?'
+ ]
+ },
+ favorite_books: {
+ label: 'Favorite Books',
+ description: 'Books that shaped your thinking',
+ targetDoc: 'BOOKS.md',
+ targetCategory: 'entertainment',
+ questions: [
+ 'What book fundamentally changed how you see the world?',
+ 'Which book do you find yourself re-reading or recommending most?',
+ 'What fiction shaped your values or aspirations?'
+ ]
+ },
+ favorite_movies: {
+ label: 'Favorite Movies',
+ description: 'Films that resonate with your aesthetic and values',
+ targetDoc: 'MOVIES.md',
+ targetCategory: 'entertainment',
+ questions: [
+ 'What film captures your aesthetic sensibility?',
+ 'Which movie do you quote or reference most often?',
+ 'What film made you think differently about a topic?'
+ ]
+ },
+ music_taste: {
+ label: 'Music Taste',
+ description: 'Music as cognitive infrastructure',
+ targetDoc: 'MUSIC.md',
+ targetCategory: 'audio',
+ questions: [
+ 'What album do you use for deep focus work?',
+ 'What music captures your emotional baseline?',
+ 'Describe your relationship with music - is it background or active engagement?'
+ ]
+ },
+ communication: {
+ label: 'Communication Style',
+ description: 'How you prefer to give and receive information',
+ targetDoc: 'COMMUNICATION.md',
+ targetCategory: 'social',
+ questions: [
+ 'How do you prefer to receive critical feedback?',
+ 'Do you prefer direct confrontation or diplomatic approach in disagreements?',
+ 'What communication style irritates you most?'
+ ]
+ },
+ decision_making: {
+ label: 'Decision Making',
+ description: 'How you approach choices and uncertainty',
+ targetDoc: 'PREFERENCES.md',
+ targetCategory: 'core',
+ questions: [
+ 'Do you decide quickly with limited info, or deliberate extensively?',
+ 'How do you handle irreversible decisions differently from reversible ones?',
+ 'What role does intuition play in your decision-making?'
+ ]
+ },
+ values: {
+ label: 'Values',
+ description: 'Core principles that guide your actions',
+ targetDoc: 'VALUES.md',
+ targetCategory: 'core',
+ questions: [
+ 'What principle would you never compromise, even at personal cost?',
+ 'What value do you wish more people held?',
+ 'Where do you draw the line between pragmatism and principle?'
+ ]
+ },
+ aesthetics: {
+ label: 'Aesthetic Preferences',
+ description: 'Visual and design sensibilities',
+ targetDoc: 'AESTHETICS.md',
+ targetCategory: 'creative',
+ questions: [
+ 'Minimalist or maximalist - where do you fall?',
+ 'What visual style or design movement resonates with you?',
+ 'How important is aesthetic coherence in your work environment?'
+ ]
+ },
+ daily_routines: {
+ label: 'Daily Routines',
+ description: 'Habits and rhythms that structure your day',
+ targetDoc: 'ROUTINES.md',
+ targetCategory: 'lifestyle',
+ questions: [
+ 'Are you a morning person or night owl, and how does this affect your work?',
+ 'What daily ritual is non-negotiable for your productivity?',
+ 'How do you recharge - solitude, social, physical activity?'
+ ]
+ },
+ career_skills: {
+ label: 'Career & Skills',
+ description: 'Professional expertise and growth areas',
+ targetDoc: 'CAREER.md',
+ targetCategory: 'professional',
+ questions: [
+ 'What are you known for professionally?',
+ 'What skill are you actively trying to develop?',
+ 'What unique perspective does your background give you?'
+ ]
+ },
+ non_negotiables: {
+ label: 'Non-Negotiables',
+ description: 'Principles and boundaries that define your limits',
+ targetDoc: 'NON_NEGOTIABLES.md',
+ targetCategory: 'core',
+ questions: [
+ 'What principle would you never compromise, even at significant personal cost?',
+ 'What behavior in others immediately erodes your trust?',
+ 'What topic should your digital twin absolutely refuse to engage with?'
+ ]
+ },
+ decision_heuristics: {
+ label: 'Decision Heuristics',
+ description: 'Mental models and shortcuts for making choices',
+ targetDoc: 'DECISION_HEURISTICS.md',
+ targetCategory: 'core',
+ questions: [
+ 'When facing a decision with limited information, do you act quickly or wait for more data?',
+ 'How do you weigh reversible vs irreversible decisions differently?',
+ 'What role does optionality play in your decision-making?'
+ ]
+ },
+ error_intolerance: {
+ label: 'Error Intolerance',
+ description: 'What your digital twin should never do',
+ targetDoc: 'ERROR_INTOLERANCE.md',
+ targetCategory: 'core',
+ questions: [
+ 'What communication style or reasoning pattern irritates you most?',
+ 'What should your digital twin never do when responding to you?',
+ 'What type of "help" actually makes things worse for you?'
+ ]
+ }
+};
+
+// =============================================================================
+// HELPERS
+// =============================================================================
+
+function generateId() {
+ return uuidv4();
+}
+
+function now() {
+ return new Date().toISOString();
+}
+
+async function ensureSoulDir() {
+ if (!existsSync(SOUL_DIR)) {
+ await mkdir(SOUL_DIR, { recursive: true });
+ console.log(`🧬 Created soul data directory: ${SOUL_DIR}`);
+ }
+}
+
+// =============================================================================
+// META / SETTINGS
+// =============================================================================
+
+export async function loadMeta() {
+ if (cache.meta.data && (Date.now() - cache.meta.timestamp) < CACHE_TTL_MS) {
+ return cache.meta.data;
+ }
+
+ await ensureSoulDir();
+
+ if (!existsSync(META_FILE)) {
+ // Scan existing documents and build initial meta
+ const meta = await buildInitialMeta();
+ await saveMeta(meta);
+ return meta;
+ }
+
+ const content = await readFile(META_FILE, 'utf-8');
+ const parsed = JSON.parse(content);
+ const validated = soulMetaSchema.safeParse(parsed);
+
+ cache.meta.data = validated.success ? validated.data : { ...DEFAULT_META, ...parsed };
+ cache.meta.timestamp = Date.now();
+ return cache.meta.data;
+}
+
+async function buildInitialMeta() {
+ const meta = { ...DEFAULT_META };
+
+ const files = await readdir(SOUL_DIR).catch(() => []);
+ const mdFiles = files.filter(f => f.endsWith('.md'));
+
+ for (const file of mdFiles) {
+ const content = await readFile(join(SOUL_DIR, file), 'utf-8').catch(() => '');
+ const title = extractTitle(content) || file.replace('.md', '');
+ const category = inferCategory(file);
+ const version = extractVersion(content);
+
+ meta.documents.push({
+ id: generateId(),
+ filename: file,
+ title,
+ category,
+ version,
+ enabled: true,
+ priority: getPriorityForFile(file),
+ weight: 5 // Default weight
+ });
+ }
+
+ // Sort by priority
+ meta.documents.sort((a, b) => a.priority - b.priority);
+
+ return meta;
+}
+
+function extractTitle(content) {
+ const match = content.match(/^#\s+(.+)/m);
+ return match ? match[1].trim() : null;
+}
+
+function extractVersion(content) {
+ const match = content.match(/\*\*Version:\*\*\s*([\d.]+)/);
+ return match ? match[1] : null;
+}
+
+function inferCategory(filename) {
+ const upper = filename.toUpperCase();
+
+ // Audio/Music
+ if (upper.startsWith('AUDIO') || upper.includes('MUSIC')) return 'audio';
+
+ // Behavioral tests
+ if (upper.includes('BEHAVIORAL') || upper.includes('TEST_SUITE')) return 'behavioral';
+
+ // Entertainment (movies, books, TV, games)
+ if (upper.includes('MOVIE') || upper.includes('FILM') || upper.includes('BOOK') ||
+ upper.includes('TV') || upper.includes('GAME') || upper.includes('ENTERTAINMENT')) return 'entertainment';
+
+ // Professional
+ if (upper.includes('CAREER') || upper.includes('SKILL') || upper.includes('WORK') ||
+ upper.includes('PROFESSIONAL')) return 'professional';
+
+ // Lifestyle
+ if (upper.includes('ROUTINE') || upper.includes('HABIT') || upper.includes('HEALTH') ||
+ upper.includes('LIFESTYLE') || upper.includes('DAILY')) return 'lifestyle';
+
+ // Social
+ if (upper.includes('SOCIAL') || upper.includes('COMMUNICATION') ||
+ upper.includes('RELATIONSHIP')) return 'social';
+
+ // Creative
+ if (upper.includes('AESTHETIC') || upper.includes('CREATIVE') || upper.includes('ART') ||
+ upper.includes('DESIGN')) return 'creative';
+
+ // Enrichment (generic enrichment outputs)
+ if (['MEMORIES.md', 'FAVORITES.md', 'PREFERENCES.md'].includes(filename)) return 'enrichment';
+
+ // Default to core identity
+ return 'core';
+}
+
+function getPriorityForFile(filename) {
+ const priorities = {
+ 'SOUL.md': 1,
+ 'Expanded.md': 2,
+ 'BEHAVIORAL_TEST_SUITE.md': 100
+ };
+ return priorities[filename] || 50;
+}
+
+export async function saveMeta(meta) {
+ await ensureSoulDir();
+ await writeFile(META_FILE, JSON.stringify(meta, null, 2));
+ cache.meta.data = meta;
+ cache.meta.timestamp = Date.now();
+ soulEvents.emit('meta:changed', meta);
+}
+
+export async function updateMeta(updates) {
+ const meta = await loadMeta();
+ const updated = { ...meta, ...updates };
+ await saveMeta(updated);
+ return updated;
+}
+
+export async function updateSettings(settings) {
+ const meta = await loadMeta();
+ meta.settings = { ...meta.settings, ...settings };
+ await saveMeta(meta);
+ return meta.settings;
+}
+
+// =============================================================================
+// DOCUMENT OPERATIONS
+// =============================================================================
+
+export async function getDocuments() {
+ const meta = await loadMeta();
+ const documents = [];
+
+ for (const doc of meta.documents) {
+ const filePath = join(SOUL_DIR, doc.filename);
+ const exists = existsSync(filePath);
+
+ if (exists) {
+ const stats = await stat(filePath);
+ documents.push({
+ ...doc,
+ lastModified: stats.mtime.toISOString(),
+ size: stats.size
+ });
+ }
+ }
+
+ return documents;
+}
+
+export async function getDocumentById(id) {
+ const meta = await loadMeta();
+ const docMeta = meta.documents.find(d => d.id === id);
+
+ if (!docMeta) return null;
+
+ const filePath = join(SOUL_DIR, docMeta.filename);
+ if (!existsSync(filePath)) return null;
+
+ const content = await readFile(filePath, 'utf-8');
+ const stats = await stat(filePath);
+
+ return {
+ ...docMeta,
+ content,
+ lastModified: stats.mtime.toISOString(),
+ size: stats.size
+ };
+}
+
+export async function createDocument(data) {
+ await ensureSoulDir();
+
+ const meta = await loadMeta();
+ const filePath = join(SOUL_DIR, data.filename);
+
+ // Check if file already exists
+ if (existsSync(filePath)) {
+ throw new Error(`Document ${data.filename} already exists`);
+ }
+
+ // Write the file
+ await writeFile(filePath, data.content);
+
+ // Add to meta
+ const docMeta = {
+ id: generateId(),
+ filename: data.filename,
+ title: data.title,
+ category: data.category,
+ version: extractVersion(data.content),
+ enabled: data.enabled !== false,
+ priority: data.priority || 50,
+ weight: data.weight || 5
+ };
+
+ meta.documents.push(docMeta);
+ meta.documents.sort((a, b) => a.priority - b.priority);
+ await saveMeta(meta);
+
+ console.log(`🧬 Created soul document: ${data.filename}`);
+ return { ...docMeta, content: data.content };
+}
+
+export async function updateDocument(id, updates) {
+ const meta = await loadMeta();
+ const docIndex = meta.documents.findIndex(d => d.id === id);
+
+ if (docIndex === -1) return null;
+
+ const docMeta = meta.documents[docIndex];
+ const filePath = join(SOUL_DIR, docMeta.filename);
+
+ // Update file content if provided
+ if (updates.content) {
+ await writeFile(filePath, updates.content);
+ docMeta.version = extractVersion(updates.content);
+ }
+
+ // Update metadata
+ if (updates.title) docMeta.title = updates.title;
+ if (updates.enabled !== undefined) docMeta.enabled = updates.enabled;
+ if (updates.priority !== undefined) {
+ docMeta.priority = updates.priority;
+ meta.documents.sort((a, b) => a.priority - b.priority);
+ }
+ if (updates.weight !== undefined) docMeta.weight = updates.weight;
+
+ meta.documents[docIndex] = docMeta;
+ await saveMeta(meta);
+
+ console.log(`🧬 Updated soul document: ${docMeta.filename}`);
+ return await getDocumentById(id);
+}
+
+export async function deleteDocument(id) {
+ const meta = await loadMeta();
+ const docIndex = meta.documents.findIndex(d => d.id === id);
+
+ if (docIndex === -1) return false;
+
+ const docMeta = meta.documents[docIndex];
+ const filePath = join(SOUL_DIR, docMeta.filename);
+
+ // Delete file
+ if (existsSync(filePath)) {
+ await unlink(filePath);
+ }
+
+ // Remove from meta
+ meta.documents.splice(docIndex, 1);
+ await saveMeta(meta);
+
+ console.log(`🧬 Deleted soul document: ${docMeta.filename}`);
+ return true;
+}
+
+// =============================================================================
+// BEHAVIORAL TESTING
+// =============================================================================
+
+export async function parseTestSuite() {
+ if (cache.tests.data && (Date.now() - cache.tests.timestamp) < CACHE_TTL_MS) {
+ return cache.tests.data;
+ }
+
+ const testFile = join(SOUL_DIR, 'BEHAVIORAL_TEST_SUITE.md');
+ if (!existsSync(testFile)) {
+ return [];
+ }
+
+ const content = await readFile(testFile, 'utf-8');
+ const tests = [];
+
+ // Parse test blocks using regex
+ const testPattern = /### Test (\d+): (.+?)\n\n\*\*Prompt\*\*\s*\n([\s\S]*?)\n\n\*\*Expected Behavior\*\*\s*\n([\s\S]*?)\n\n\*\*Failure Signals\*\*\s*\n([\s\S]*?)(?=\n---|\n### Test|\n## |$)/g;
+
+ let match;
+ while ((match = testPattern.exec(content)) !== null) {
+ tests.push({
+ testId: parseInt(match[1]),
+ testName: match[2].trim(),
+ prompt: match[3].trim().replace(/^"|"$/g, ''),
+ expectedBehavior: match[4].trim(),
+ failureSignals: match[5].trim()
+ });
+ }
+
+ cache.tests.data = tests;
+ cache.tests.timestamp = Date.now();
+
+ return tests;
+}
+
+export async function runTests(providerId, model, testIds = null) {
+ const tests = await parseTestSuite();
+ const soulContext = await getSoulForPrompt();
+
+ const provider = await getProviderById(providerId);
+ if (!provider || !provider.enabled) {
+ throw new Error(`Provider ${providerId} not found or disabled`);
+ }
+
+ // Filter tests if specific IDs provided
+ const testsToRun = testIds
+ ? tests.filter(t => testIds.includes(t.testId))
+ : tests;
+
+ const results = [];
+ let passed = 0, failed = 0, partial = 0;
+
+ for (const test of testsToRun) {
+ const result = await runSingleTest(test, soulContext, providerId, model);
+ results.push(result);
+
+ if (result.result === 'passed') passed++;
+ else if (result.result === 'failed') failed++;
+ else if (result.result === 'partial') partial++;
+ }
+
+ // Save to history
+ const historyEntry = {
+ runId: generateId(),
+ providerId,
+ model,
+ score: testsToRun.length > 0 ? (passed + partial * 0.5) / testsToRun.length : 0,
+ passed,
+ failed,
+ partial,
+ total: testsToRun.length,
+ timestamp: now()
+ };
+
+ const meta = await loadMeta();
+ meta.testHistory.unshift(historyEntry);
+ meta.testHistory = meta.testHistory.slice(0, 50); // Keep last 50 runs
+ await saveMeta(meta);
+
+ console.log(`🧬 Test run complete: ${passed}/${testsToRun.length} passed`);
+
+ return {
+ ...historyEntry,
+ results
+ };
+}
+
+async function runSingleTest(test, soulContext, providerId, model) {
+ const provider = await getProviderById(providerId);
+
+ // Build the prompt with soul context as system prompt
+ const systemPrompt = `You are embodying the following identity. Respond as this person would, based on the soul document below:\n\n${soulContext}`;
+
+ let response = '';
+
+ if (provider.type === 'api') {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) {
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ }
+
+ const apiResponse = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ model,
+ messages: [
+ { role: 'system', content: systemPrompt },
+ { role: 'user', content: test.prompt }
+ ],
+ temperature: 0.7,
+ max_tokens: 1000
+ })
+ });
+
+ if (!apiResponse.ok) {
+ throw new Error(`API error: ${apiResponse.status}`);
+ }
+
+ const data = await apiResponse.json();
+ response = data.choices?.[0]?.message?.content || '';
+ } else {
+ // For CLI providers, combine system prompt with user prompt
+ const { spawn } = await import('child_process');
+ const combinedPrompt = `${systemPrompt}\n\nUser: ${test.prompt}`;
+
+ response = await new Promise((resolve, reject) => {
+ const args = [...(provider.args || []), combinedPrompt];
+ let output = '';
+
+ const child = spawn(provider.command, args, {
+ env: { ...process.env, ...provider.envVars },
+ shell: false
+ });
+
+ child.stdout.on('data', (data) => { output += data.toString(); });
+ child.stderr.on('data', (data) => { output += data.toString(); });
+ child.on('close', () => resolve(output));
+ child.on('error', reject);
+
+ setTimeout(() => { child.kill(); reject(new Error('Timeout')); }, 60000);
+ });
+ }
+
+ // Score the response
+ const scoring = await scoreTestResponse(test, response, providerId, model);
+
+ return {
+ testId: test.testId,
+ testName: test.testName,
+ prompt: test.prompt,
+ expectedBehavior: test.expectedBehavior,
+ failureSignals: test.failureSignals,
+ response,
+ result: scoring.result,
+ reasoning: scoring.reasoning
+ };
+}
+
+async function scoreTestResponse(test, response, providerId, model) {
+ // Use AI to score the response
+ const prompt = await buildPrompt('soul-test-scorer', {
+ testName: test.testName,
+ prompt: test.prompt,
+ expectedBehavior: test.expectedBehavior,
+ failureSignals: test.failureSignals,
+ response: response.substring(0, 2000) // Truncate for scoring
+ }).catch(() => null);
+
+ if (!prompt) {
+ // Fallback: simple keyword matching
+ const hasFailureSignals = test.failureSignals.toLowerCase().split('\n')
+ .some(signal => response.toLowerCase().includes(signal.trim().slice(2)));
+
+ return {
+ result: hasFailureSignals ? 'failed' : 'passed',
+ reasoning: 'Automated keyword matching (prompt template unavailable)'
+ };
+ }
+
+ const provider = await getProviderById(providerId);
+
+ if (provider.type === 'api') {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) {
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ }
+
+ const apiResponse = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.1,
+ max_tokens: 500
+ })
+ });
+
+ if (apiResponse.ok) {
+ const data = await apiResponse.json();
+ const scoringResponse = data.choices?.[0]?.message?.content || '';
+ return parseScoreResponse(scoringResponse);
+ }
+ }
+
+ // Default fallback
+ return { result: 'partial', reasoning: 'Unable to score - defaulting to partial' };
+}
+
+function parseScoreResponse(response) {
+ const lower = response.toLowerCase();
+
+ let result = 'partial';
+ if (lower.includes('"result": "passed"') || lower.includes('result: passed')) {
+ result = 'passed';
+ } else if (lower.includes('"result": "failed"') || lower.includes('result: failed')) {
+ result = 'failed';
+ }
+
+ // Extract reasoning
+ const reasoningMatch = response.match(/"reasoning":\s*"([^"]+)"/);
+ const reasoning = reasoningMatch ? reasoningMatch[1] : response.substring(0, 200);
+
+ return { result, reasoning };
+}
+
+export async function getTestHistory(limit = 10) {
+ const meta = await loadMeta();
+ return meta.testHistory.slice(0, limit);
+}
+
+// =============================================================================
+// ENRICHMENT
+// =============================================================================
+
+export function getEnrichmentCategories() {
+ return Object.entries(ENRICHMENT_CATEGORIES).map(([key, config]) => ({
+ id: key,
+ label: config.label,
+ description: config.description,
+ targetDoc: config.targetDoc,
+ sampleQuestions: config.questions.length
+ }));
+}
+
+export async function generateEnrichmentQuestion(category, providerOverride, modelOverride) {
+ const config = ENRICHMENT_CATEGORIES[category];
+ if (!config) {
+ throw new Error(`Unknown enrichment category: ${category}`);
+ }
+
+ const meta = await loadMeta();
+ const questionsAnswered = meta.enrichment.questionsAnswered?.[category] || 0;
+
+ // Use predefined questions first
+ if (questionsAnswered < config.questions.length) {
+ return {
+ questionId: generateId(),
+ category,
+ question: config.questions[questionsAnswered],
+ isGenerated: false,
+ questionNumber: questionsAnswered + 1,
+ totalQuestions: config.questions.length
+ };
+ }
+
+ // Generate follow-up question using AI
+ const existingSoul = await getSoulForPrompt({ maxTokens: 2000 });
+
+ const prompt = await buildPrompt('soul-enrichment', {
+ category,
+ categoryLabel: config.label,
+ categoryDescription: config.description,
+ existingSoul,
+ questionsAnswered
+ }).catch(() => null);
+
+ if (!prompt) {
+ return {
+ questionId: generateId(),
+ category,
+ question: config.questions[0], // Fallback to first question
+ isGenerated: false,
+ questionNumber: questionsAnswered + 1,
+ totalQuestions: config.questions.length
+ };
+ }
+
+ const provider = providerOverride
+ ? await getProviderById(providerOverride)
+ : await getActiveProvider();
+
+ if (!provider) {
+ throw new Error('No AI provider available');
+ }
+
+ const model = modelOverride || provider.defaultModel;
+
+ let question = config.questions[0]; // Fallback
+
+ 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.8,
+ max_tokens: 200
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ question = data.choices?.[0]?.message?.content?.trim() || question;
+ }
+ }
+
+ return {
+ questionId: generateId(),
+ category,
+ question,
+ isGenerated: true,
+ questionNumber: questionsAnswered + 1,
+ totalQuestions: null // Unlimited for generated questions
+ };
+}
+
+export async function processEnrichmentAnswer(data) {
+ const { category, question, answer, providerOverride, modelOverride } = data;
+ const config = ENRICHMENT_CATEGORIES[category];
+
+ if (!config) {
+ throw new Error(`Unknown enrichment category: ${category}`);
+ }
+
+ // Generate content to add to the target document
+ const provider = providerOverride
+ ? await getProviderById(providerOverride)
+ : await getActiveProvider();
+
+ let formattedContent = `### ${question}\n\n${answer}\n\n`;
+
+ if (provider) {
+ const prompt = await buildPrompt('soul-enrichment-process', {
+ category,
+ categoryLabel: config.label,
+ question,
+ answer
+ }).catch(() => null);
+
+ if (prompt && 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: providerOverride || provider.defaultModel,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.3,
+ max_tokens: 500
+ })
+ });
+
+ if (response.ok) {
+ const respData = await response.json();
+ formattedContent = respData.choices?.[0]?.message?.content?.trim() || formattedContent;
+ }
+ }
+ }
+
+ // Append to target document
+ const targetPath = join(SOUL_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);
+
+ // Update meta
+ const meta = await loadMeta();
+ if (!meta.enrichment.questionsAnswered) {
+ meta.enrichment.questionsAnswered = {};
+ }
+ meta.enrichment.questionsAnswered[category] =
+ (meta.enrichment.questionsAnswered[category] || 0) + 1;
+ meta.enrichment.lastSession = now();
+
+ // Check if we've completed a category (3+ questions answered)
+ 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);
+
+ console.log(`🧬 Enrichment answer processed for ${category}`);
+
+ return {
+ category,
+ targetDoc: config.targetDoc,
+ contentAdded: formattedContent
+ };
+}
+
+export async function getEnrichmentProgress() {
+ const meta = await loadMeta();
+ const categories = Object.keys(ENRICHMENT_CATEGORIES);
+
+ const progress = {};
+ for (const cat of categories) {
+ const answered = meta.enrichment.questionsAnswered?.[cat] || 0;
+ const baseQuestions = ENRICHMENT_CATEGORIES[cat].questions.length;
+ progress[cat] = {
+ answered,
+ baseQuestions,
+ completed: meta.enrichment.completedCategories.includes(cat),
+ percentage: Math.min(100, Math.round((answered / baseQuestions) * 100))
+ };
+ }
+
+ return {
+ categories: progress,
+ completedCount: meta.enrichment.completedCategories.length,
+ totalCategories: categories.length,
+ lastSession: meta.enrichment.lastSession
+ };
+}
+
+// =============================================================================
+// EXPORT
+// =============================================================================
+
+export function getExportFormats() {
+ return [
+ { id: 'system_prompt', label: 'System Prompt', description: 'Combined markdown for direct injection' },
+ { id: 'claude_md', label: 'CLAUDE.md', description: 'Format for Claude Code integration' },
+ { id: 'json', label: 'JSON', description: 'Structured JSON for API integration' },
+ { id: 'individual', label: 'Individual Files', description: 'Separate files for each document' }
+ ];
+}
+
+export async function exportSoul(format, documentIds = null, includeDisabled = false) {
+ const meta = await loadMeta();
+ let docs = meta.documents;
+
+ // Filter by IDs if provided
+ if (documentIds) {
+ docs = docs.filter(d => documentIds.includes(d.id));
+ }
+
+ // Filter disabled unless explicitly included
+ if (!includeDisabled) {
+ docs = docs.filter(d => d.enabled);
+ }
+
+ // Exclude behavioral test suite from exports
+ docs = docs.filter(d => d.category !== 'behavioral');
+
+ // Sort by priority
+ docs.sort((a, b) => a.priority - b.priority);
+
+ // Load content for each document
+ const documentsWithContent = [];
+ for (const doc of docs) {
+ const filePath = join(SOUL_DIR, doc.filename);
+ if (existsSync(filePath)) {
+ const content = await readFile(filePath, 'utf-8');
+ documentsWithContent.push({ ...doc, content });
+ }
+ }
+
+ switch (format) {
+ case 'system_prompt':
+ return exportAsSystemPrompt(documentsWithContent);
+ case 'claude_md':
+ return exportAsClaudeMd(documentsWithContent);
+ case 'json':
+ return exportAsJson(documentsWithContent);
+ case 'individual':
+ return exportAsIndividual(documentsWithContent);
+ default:
+ throw new Error(`Unknown export format: ${format}`);
+ }
+}
+
+function exportAsSystemPrompt(docs) {
+ let output = '# User Identity & Persona (Soul)\n\n';
+ output += 'The following describes the identity, values, and preferences of the user you are assisting. ';
+ output += 'Use this context to align your responses with their communication style, values, and goals.\n\n';
+ output += '---\n\n';
+
+ for (const doc of docs) {
+ output += doc.content + '\n\n---\n\n';
+ }
+
+ return {
+ format: 'system_prompt',
+ content: output.trim(),
+ documentCount: docs.length,
+ tokenEstimate: Math.ceil(output.length / 4)
+ };
+}
+
+function exportAsClaudeMd(docs) {
+ let output = '# Soul - User Identity\n\n';
+ output += '> This section defines the identity, values, and preferences of the user.\n\n';
+
+ for (const doc of docs) {
+ // Remove the main header from each doc to avoid duplication
+ const content = doc.content.replace(/^#\s+.+\n+/, '');
+ output += `## ${doc.title}\n\n${content}\n\n`;
+ }
+
+ return {
+ format: 'claude_md',
+ content: output.trim(),
+ documentCount: docs.length,
+ tokenEstimate: Math.ceil(output.length / 4)
+ };
+}
+
+function exportAsJson(docs) {
+ const structured = {
+ version: '1.0.0',
+ exportedAt: now(),
+ documents: docs.map(doc => ({
+ id: doc.id,
+ title: doc.title,
+ category: doc.category,
+ content: doc.content
+ })),
+ metadata: {
+ totalDocuments: docs.length,
+ categories: [...new Set(docs.map(d => d.category))]
+ }
+ };
+
+ const jsonString = JSON.stringify(structured, null, 2);
+
+ return {
+ format: 'json',
+ content: jsonString,
+ documentCount: docs.length,
+ tokenEstimate: Math.ceil(jsonString.length / 4)
+ };
+}
+
+function exportAsIndividual(docs) {
+ return {
+ format: 'individual',
+ files: docs.map(doc => ({
+ filename: doc.filename,
+ title: doc.title,
+ category: doc.category,
+ content: doc.content
+ })),
+ documentCount: docs.length,
+ tokenEstimate: docs.reduce((sum, d) => sum + Math.ceil(d.content.length / 4), 0)
+ };
+}
+
+// =============================================================================
+// COS INTEGRATION
+// =============================================================================
+
+export async function getSoulForPrompt(options = {}) {
+ const { maxTokens = 4000 } = options;
+ const meta = await loadMeta();
+
+ if (!meta.settings.autoInjectToCoS) {
+ return '';
+ }
+
+ // Get enabled documents sorted by weight (desc) then priority (asc)
+ // Higher weight = more important = included first
+ const docs = meta.documents
+ .filter(d => d.enabled && d.category !== 'behavioral')
+ .sort((a, b) => {
+ const weightA = a.weight || 5;
+ const weightB = b.weight || 5;
+ if (weightB !== weightA) return weightB - weightA; // Higher weight first
+ return a.priority - b.priority; // Then by priority
+ });
+
+ let output = '';
+ let tokenCount = 0;
+ const maxChars = maxTokens * 4; // Rough char-to-token estimate
+
+ for (const doc of docs) {
+ const filePath = join(SOUL_DIR, doc.filename);
+ if (!existsSync(filePath)) continue;
+
+ const content = await readFile(filePath, 'utf-8');
+
+ if (tokenCount + content.length > maxChars) {
+ // Truncate if we're over budget
+ const remaining = maxChars - tokenCount;
+ if (remaining > 500) {
+ output += content.substring(0, remaining) + '\n\n[Truncated due to token limit]\n';
+ }
+ break;
+ }
+
+ output += content + '\n\n---\n\n';
+ tokenCount += content.length;
+ }
+
+ return output.trim();
+}
+
+// =============================================================================
+// STATUS & SUMMARY
+// =============================================================================
+
+export async function getSoulStatus() {
+ const meta = await loadMeta();
+ const documents = await getDocuments();
+ const testHistory = meta.testHistory.slice(0, 5);
+ const enrichmentProgress = await getEnrichmentProgress();
+
+ // Calculate health score
+ const docScore = Math.min(1, documents.filter(d => d.enabled).length / 5);
+ const testScore = testHistory.length > 0 ? testHistory[0].score : 0;
+ const enrichScore = enrichmentProgress.completedCount / enrichmentProgress.totalCategories;
+
+ const healthScore = Math.round(((docScore + testScore + enrichScore) / 3) * 100);
+
+ return {
+ healthScore,
+ documentCount: documents.length,
+ enabledDocuments: documents.filter(d => d.enabled).length,
+ documentsByCategory: {
+ core: documents.filter(d => d.category === 'core').length,
+ audio: documents.filter(d => d.category === 'audio').length,
+ behavioral: documents.filter(d => d.category === 'behavioral').length,
+ enrichment: documents.filter(d => d.category === 'enrichment').length
+ },
+ lastTestRun: testHistory[0] || null,
+ enrichmentProgress: {
+ completedCategories: enrichmentProgress.completedCount,
+ totalCategories: enrichmentProgress.totalCategories
+ },
+ settings: meta.settings
+ };
+}
+
+// =============================================================================
+// VALIDATION & ANALYSIS
+// =============================================================================
+
+// Required sections for a complete soul
+const REQUIRED_SECTIONS = [
+ {
+ id: 'identity',
+ label: 'Identity Basics',
+ description: 'Name, role, and one-liner description',
+ keywords: ['name', 'role', 'who i am', 'identity', 'about me'],
+ suggestedEnrichment: null,
+ suggestedDoc: 'SOUL.md'
+ },
+ {
+ id: 'values',
+ label: 'Core Values',
+ description: 'At least 3 clearly defined principles',
+ keywords: ['values', 'principles', 'believe', 'important to me'],
+ suggestedEnrichment: 'values',
+ suggestedDoc: 'VALUES.md'
+ },
+ {
+ id: 'communication',
+ label: 'Communication Style',
+ description: 'How you prefer to give and receive information',
+ keywords: ['communication', 'prefer', 'feedback', 'style', 'tone'],
+ suggestedEnrichment: 'communication',
+ suggestedDoc: 'COMMUNICATION.md'
+ },
+ {
+ id: 'decision_making',
+ label: 'Decision Making',
+ description: 'How you approach choices and uncertainty',
+ keywords: ['decision', 'choose', 'uncertainty', 'risk', 'intuition'],
+ suggestedEnrichment: 'decision_heuristics',
+ suggestedDoc: 'DECISION_HEURISTICS.md'
+ },
+ {
+ id: 'non_negotiables',
+ label: 'Non-Negotiables',
+ description: 'Principles and boundaries you never compromise',
+ keywords: ['non-negotiable', 'never', 'boundary', 'refuse', 'limit'],
+ suggestedEnrichment: 'non_negotiables',
+ suggestedDoc: 'NON_NEGOTIABLES.md'
+ },
+ {
+ id: 'error_intolerance',
+ label: 'Error Intolerance',
+ description: 'What your digital twin should never do',
+ keywords: ['never do', 'irritate', 'annoy', 'hate', 'worst'],
+ suggestedEnrichment: 'error_intolerance',
+ suggestedDoc: 'ERROR_INTOLERANCE.md'
+ }
+];
+
+export async function validateCompleteness() {
+ const documents = await getDocuments();
+ const enabledDocs = documents.filter(d => d.enabled && d.category !== 'behavioral');
+
+ // Load content for all enabled documents
+ const contents = [];
+ for (const doc of enabledDocs) {
+ const filePath = join(SOUL_DIR, doc.filename);
+ if (existsSync(filePath)) {
+ const content = await readFile(filePath, 'utf-8');
+ contents.push({ doc, content: content.toLowerCase() });
+ }
+ }
+
+ const allContent = contents.map(c => c.content).join('\n');
+ const found = [];
+ const missing = [];
+
+ for (const section of REQUIRED_SECTIONS) {
+ const hasKeywords = section.keywords.some(kw => allContent.includes(kw.toLowerCase()));
+ const hasDoc = enabledDocs.some(d =>
+ d.filename.toLowerCase().includes(section.id.replace('_', '')) ||
+ d.title.toLowerCase().includes(section.label.toLowerCase())
+ );
+
+ if (hasKeywords || hasDoc) {
+ found.push(section.id);
+ } else {
+ missing.push({
+ id: section.id,
+ label: section.label,
+ description: section.description,
+ suggestion: section.suggestedEnrichment
+ ? `Answer questions in the "${ENRICHMENT_CATEGORIES[section.suggestedEnrichment]?.label}" enrichment category`
+ : `Create a ${section.suggestedDoc} document`,
+ enrichmentCategory: section.suggestedEnrichment
+ });
+ }
+ }
+
+ const score = Math.round((found.length / REQUIRED_SECTIONS.length) * 100);
+
+ return {
+ score,
+ total: REQUIRED_SECTIONS.length,
+ found: found.length,
+ missing,
+ suggestions: missing.map(m => m.suggestion)
+ };
+}
+
+export async function detectContradictions(providerId, model) {
+ const documents = await getDocuments();
+ const enabledDocs = documents.filter(d => d.enabled && d.category !== 'behavioral');
+
+ if (enabledDocs.length < 2) {
+ return { issues: [], message: 'Need at least 2 documents to detect contradictions' };
+ }
+
+ // Load all document contents
+ let combinedContent = '';
+ for (const doc of enabledDocs) {
+ const filePath = join(SOUL_DIR, doc.filename);
+ if (existsSync(filePath)) {
+ const content = await readFile(filePath, 'utf-8');
+ combinedContent += `\n\n## Document: ${doc.filename}\n\n${content}`;
+ }
+ }
+
+ // Build the prompt
+ const prompt = await buildPrompt('soul-contradiction-detector', {
+ soulContent: combinedContent.substring(0, 15000) // Limit to avoid token limits
+ }).catch(() => null);
+
+ if (!prompt) {
+ return { issues: [], error: 'Contradiction detector prompt template not found' };
+ }
+
+ const provider = await getProviderById(providerId);
+ if (!provider || !provider.enabled) {
+ return { issues: [], 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: 2000
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ const responseText = data.choices?.[0]?.message?.content || '';
+ return parseContradictionResponse(responseText);
+ }
+ }
+
+ return { issues: [], error: 'Failed to analyze contradictions' };
+}
+
+function parseContradictionResponse(response) {
+ // Try to extract JSON from the response
+ const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
+ if (jsonMatch) {
+ const parsed = JSON.parse(jsonMatch[1]);
+ return { issues: parsed.issues || [], summary: parsed.summary };
+ }
+
+ // Fallback: try direct JSON parse
+ if (response.trim().startsWith('{') || response.trim().startsWith('[')) {
+ const parsed = JSON.parse(response);
+ return { issues: parsed.issues || parsed || [], summary: parsed.summary };
+ }
+
+ return { issues: [], rawResponse: response };
+}
+
+export async function generateDynamicTests(providerId, model) {
+ const soulContent = await getSoulForPrompt({ maxTokens: 8000 });
+
+ if (!soulContent || soulContent.length < 100) {
+ return { tests: [], error: 'Insufficient soul content to generate tests' };
+ }
+
+ const prompt = await buildPrompt('soul-test-generator', {
+ soulContent
+ }).catch(() => null);
+
+ if (!prompt) {
+ return { tests: [], error: 'Test generator prompt template not found' };
+ }
+
+ const provider = await getProviderById(providerId);
+ if (!provider || !provider.enabled) {
+ return { tests: [], 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.7,
+ max_tokens: 3000
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ const responseText = data.choices?.[0]?.message?.content || '';
+ return parseGeneratedTests(responseText);
+ }
+ }
+
+ return { tests: [], error: 'Failed to generate tests' };
+}
+
+function parseGeneratedTests(response) {
+ // Try to extract JSON from the response
+ const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
+ if (jsonMatch) {
+ const parsed = JSON.parse(jsonMatch[1]);
+ return { tests: parsed.tests || parsed || [] };
+ }
+
+ // Fallback: try direct JSON parse
+ if (response.trim().startsWith('{') || response.trim().startsWith('[')) {
+ const parsed = JSON.parse(response);
+ return { tests: parsed.tests || parsed || [] };
+ }
+
+ return { tests: [], rawResponse: response };
+}
+
+export async function analyzeWritingSamples(samples, providerId, model) {
+ if (!samples || samples.length === 0) {
+ return { error: 'No writing samples provided' };
+ }
+
+ const combinedSamples = samples.map((s, i) => `--- Sample ${i + 1} ---\n${s}`).join('\n\n');
+
+ const prompt = await buildPrompt('soul-writing-analyzer', {
+ samples: combinedSamples
+ }).catch(() => null);
+
+ if (!prompt) {
+ return { error: 'Writing analyzer 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.5,
+ max_tokens: 2000
+ })
+ });
+
+ if (response.ok) {
+ const data = await response.json();
+ const responseText = data.choices?.[0]?.message?.content || '';
+ return parseWritingAnalysis(responseText);
+ }
+ }
+
+ return { error: 'Failed to analyze writing samples' };
+}
+
+function parseWritingAnalysis(response) {
+ // Try to extract JSON
+ const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
+ if (jsonMatch) {
+ const parsed = JSON.parse(jsonMatch[1]);
+ return {
+ analysis: parsed.analysis || parsed,
+ suggestedContent: parsed.suggestedContent || parsed.document || ''
+ };
+ }
+
+ // Extract markdown content for document if present
+ const mdMatch = response.match(/```markdown\s*([\s\S]*?)\s*```/);
+ const suggestedContent = mdMatch ? mdMatch[1] : '';
+
+ return {
+ analysis: { rawResponse: response },
+ suggestedContent
+ };
+}