Skip to content

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

feat(digital-twin): add list enrichment and enhance document management

Adam Eivy9f5f94a696ee
diff --git a/client/src/components/digital-twin/ListEnrichment.jsx b/client/src/components/digital-twin/ListEnrichment.jsx
new file mode 100644
index 0000000000..04ca91b4f4
--- /dev/null
+++ b/client/src/components/digital-twin/ListEnrichment.jsx
@@ -0,0 +1,427 @@
+import { useState, useEffect } from 'react';
+import {
+ ArrowLeft,
+ Plus,
+ X,
+ Sparkles,
+ RefreshCw,
+ Save,
+ Edit3,
+ Eye,
+ ChevronDown,
+ ChevronRight,
+ Check
+} from 'lucide-react';
+import * as api from '../../services/api';
+import toast from 'react-hot-toast';
+
+import { ENRICHMENT_CATEGORIES } from './constants';
+
+/**
+ * List-based enrichment component for books, movies, music
+ * Allows users to add items, analyze them with LLM, review/edit results
+ */
+export default function ListEnrichment({
+ categoryId,
+ onBack,
+ onRefresh,
+ providers,
+ selectedProvider,
+ setSelectedProvider
+}) {
+ const config = ENRICHMENT_CATEGORIES[categoryId];
+
+ // List items state
+ const [items, setItems] = useState([{ title: '', note: '' }]);
+ const [loadingItems, setLoadingItems] = useState(true);
+
+ // Analysis state
+ const [analyzing, setAnalyzing] = useState(false);
+ const [analysis, setAnalysis] = useState(null);
+
+ // Document editing state
+ const [editingDocument, setEditingDocument] = useState(false);
+ const [documentContent, setDocumentContent] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ // Expanded sections
+ const [showItemAnalysis, setShowItemAnalysis] = useState(false);
+ const [showPatterns, setShowPatterns] = useState(true);
+ const [showInsights, setShowInsights] = useState(true);
+
+ // Load existing items on mount
+ useEffect(() => {
+ loadExistingItems();
+ }, [categoryId]);
+
+ const loadExistingItems = async () => {
+ setLoadingItems(true);
+ const existingItems = await api.getEnrichmentListItems(categoryId).catch(() => []);
+ if (existingItems && existingItems.length > 0) {
+ setItems(existingItems);
+ } else {
+ setItems([{ title: '', note: '' }]);
+ }
+ setLoadingItems(false);
+ };
+
+ const addItem = () => {
+ setItems([...items, { title: '', note: '' }]);
+ };
+
+ const updateItem = (index, field, value) => {
+ const updated = [...items];
+ updated[index] = { ...updated[index], [field]: value };
+ setItems(updated);
+ };
+
+ const removeItem = (index) => {
+ if (items.length > 1) {
+ setItems(items.filter((_, i) => i !== index));
+ }
+ };
+
+ const getValidItems = () => items.filter(item => item.title.trim().length > 0);
+
+ const analyzeList = async () => {
+ const validItems = getValidItems();
+ if (validItems.length === 0) {
+ toast.error(`Add at least one ${config.itemLabel.toLowerCase()}`);
+ return;
+ }
+ if (!selectedProvider) {
+ toast.error('Select a provider first');
+ return;
+ }
+
+ setAnalyzing(true);
+ setAnalysis(null);
+
+ const result = await api.analyzeEnrichmentList(
+ categoryId,
+ validItems,
+ selectedProvider.providerId,
+ selectedProvider.model
+ ).catch(e => ({ error: e.message }));
+
+ if (result.error) {
+ toast.error(result.error);
+ } else {
+ setAnalysis(result);
+ setDocumentContent(result.suggestedDocument || '');
+ toast.success('Analysis complete');
+ }
+ setAnalyzing(false);
+ };
+
+ const saveDocument = async () => {
+ if (!documentContent.trim()) {
+ toast.error('No document content to save');
+ return;
+ }
+
+ setSaving(true);
+ const result = await api.saveEnrichmentList(
+ categoryId,
+ documentContent,
+ getValidItems()
+ ).catch(e => ({ error: e.message }));
+
+ if (result.error) {
+ toast.error(result.error);
+ } else {
+ toast.success(`Saved to ${result.targetDoc}`);
+ onRefresh?.();
+ }
+ setSaving(false);
+ };
+
+ const Icon = config?.icon || Sparkles;
+
+ if (loadingItems) {
+ 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="max-w-3xl mx-auto px-1">
+ {/* Header */}
+ <div className="mb-6 sm:mb-8">
+ <button
+ onClick={onBack}
+ className="flex items-center gap-2 text-gray-400 hover:text-white mb-4 py-2 min-h-[44px]"
+ >
+ <ArrowLeft size={18} />
+ Back to categories
+ </button>
+
+ <div className="flex items-center gap-3 sm:gap-4">
+ <div className={`p-2.5 sm:p-3 rounded-lg bg-${config?.color || 'blue'}-500/20 flex-shrink-0`}>
+ <Icon className={`w-5 h-5 sm:w-6 sm:h-6 text-${config?.color || 'blue'}-400`} />
+ </div>
+ <div className="min-w-0">
+ <h2 className="text-lg sm:text-xl font-bold text-white">{config?.label}</h2>
+ <p className="text-sm sm:text-base text-gray-400">{config?.description}</p>
+ </div>
+ </div>
+ </div>
+
+ {/* Items List */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4 sm:p-6 mb-6">
+ <h3 className="font-medium text-white mb-4 flex items-center gap-2">
+ <Icon size={18} />
+ Your {config?.label}
+ </h3>
+
+ <div className="space-y-4">
+ {items.map((item, index) => (
+ <div
+ key={index}
+ className="bg-port-bg rounded-lg border border-port-border p-4 relative group"
+ >
+ {items.length > 1 && (
+ <button
+ onClick={() => removeItem(index)}
+ className="absolute top-2 right-2 p-1.5 text-gray-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity"
+ title="Remove"
+ >
+ <X size={16} />
+ </button>
+ )}
+
+ <div className="space-y-3">
+ <div>
+ <label className="text-xs text-gray-500 uppercase tracking-wider mb-1 block">
+ {config?.itemLabel} {index + 1}
+ </label>
+ <input
+ type="text"
+ value={item.title}
+ onChange={(e) => updateItem(index, 'title', e.target.value)}
+ placeholder={config?.itemPlaceholder}
+ className="w-full px-3 py-2.5 bg-port-card border border-port-border rounded-lg text-white focus:outline-none focus:border-port-accent"
+ />
+ </div>
+
+ <div>
+ <label className="text-xs text-gray-500 uppercase tracking-wider mb-1 block">
+ Notes (optional)
+ </label>
+ <textarea
+ value={item.note}
+ onChange={(e) => updateItem(index, 'note', e.target.value)}
+ placeholder={config?.notePlaceholder}
+ rows={2}
+ className="w-full px-3 py-2.5 bg-port-card border border-port-border rounded-lg text-white resize-none focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+
+ <button
+ onClick={addItem}
+ className="mt-4 flex items-center gap-2 px-4 py-2.5 min-h-[44px] text-port-accent hover:text-white border border-port-accent/30 rounded-lg hover:border-port-accent transition-colors"
+ >
+ <Plus size={18} />
+ Add {config?.itemLabel}
+ </button>
+ </div>
+
+ {/* Provider Selection & Analyze Button */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4 sm:p-6 mb-6">
+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-4">
+ <div className="flex-1">
+ <label className="text-xs text-gray-500 uppercase tracking-wider mb-2 block">
+ Analyze with
+ </label>
+ <select
+ value={selectedProvider ? `${selectedProvider.providerId}:${selectedProvider.model}` : ''}
+ onChange={(e) => {
+ const [providerId, model] = e.target.value.split(':');
+ setSelectedProvider({ providerId, model });
+ }}
+ className="w-full px-3 py-3 min-h-[44px] 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>
+
+ <button
+ onClick={analyzeList}
+ disabled={analyzing || getValidItems().length === 0}
+ className="px-6 py-3 min-h-[48px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 sm:self-end"
+ >
+ {analyzing ? (
+ <>
+ <RefreshCw className="w-5 h-5 animate-spin" />
+ Analyzing...
+ </>
+ ) : (
+ <>
+ <Sparkles size={18} />
+ Analyze & Generate
+ </>
+ )}
+ </button>
+ </div>
+
+ <p className="text-xs text-gray-500 mt-3">
+ The AI will analyze your selections to identify patterns, themes, and personality insights.
+ </p>
+ </div>
+
+ {/* Analysis Results */}
+ {analysis && (
+ <div className="space-y-6">
+ {/* Item Analysis (collapsible) */}
+ {analysis.itemAnalysis?.length > 0 && (
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
+ <button
+ onClick={() => setShowItemAnalysis(!showItemAnalysis)}
+ className="w-full p-4 flex items-center justify-between hover:bg-port-border/30 transition-colors"
+ >
+ <h3 className="font-medium text-white flex items-center gap-2">
+ <Eye size={18} />
+ Item-by-Item Analysis
+ </h3>
+ {showItemAnalysis ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
+ </button>
+
+ {showItemAnalysis && (
+ <div className="p-4 pt-0 space-y-3">
+ {analysis.itemAnalysis.map((item, i) => (
+ <div key={i} className="p-3 bg-port-bg rounded-lg">
+ <div className="font-medium text-white mb-1">{item.title}</div>
+ <div className="text-sm text-gray-400">{item.insights}</div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Patterns */}
+ {analysis.patterns?.length > 0 && (
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
+ <button
+ onClick={() => setShowPatterns(!showPatterns)}
+ className="w-full p-4 flex items-center justify-between hover:bg-port-border/30 transition-colors"
+ >
+ <h3 className="font-medium text-white flex items-center gap-2">
+ <Sparkles size={18} />
+ Patterns Detected
+ </h3>
+ {showPatterns ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
+ </button>
+
+ {showPatterns && (
+ <div className="p-4 pt-0">
+ <ul className="space-y-2">
+ {analysis.patterns.map((pattern, i) => (
+ <li key={i} className="flex items-start gap-2 text-gray-300">
+ <Check size={16} className="text-green-400 mt-0.5 flex-shrink-0" />
+ {pattern}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Personality Insights */}
+ {analysis.personalityInsights && (
+ <div className="bg-port-card rounded-lg border border-port-border overflow-hidden">
+ <button
+ onClick={() => setShowInsights(!showInsights)}
+ className="w-full p-4 flex items-center justify-between hover:bg-port-border/30 transition-colors"
+ >
+ <h3 className="font-medium text-white flex items-center gap-2">
+ <Sparkles size={18} />
+ Personality Insights
+ </h3>
+ {showInsights ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
+ </button>
+
+ {showInsights && (
+ <div className="p-4 pt-0 space-y-3">
+ {Object.entries(analysis.personalityInsights).map(([key, value]) => (
+ <div key={key} className="p-3 bg-port-bg rounded-lg">
+ <div className="text-xs text-gray-500 uppercase tracking-wider mb-1">
+ {key.replace(/([A-Z])/g, ' $1').trim()}
+ </div>
+ <div className="text-sm text-gray-300">{value}</div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Generated Document */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4 sm:p-6">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="font-medium text-white flex items-center gap-2">
+ Generated Document: {analysis.targetDoc}
+ </h3>
+ <button
+ onClick={() => setEditingDocument(!editingDocument)}
+ className="flex items-center gap-1 text-sm text-port-accent hover:text-white"
+ >
+ <Edit3 size={14} />
+ {editingDocument ? 'Preview' : 'Edit'}
+ </button>
+ </div>
+
+ {editingDocument ? (
+ <textarea
+ value={documentContent}
+ onChange={(e) => setDocumentContent(e.target.value)}
+ rows={15}
+ className="w-full px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white font-mono text-sm resize-y focus:outline-none focus:border-port-accent"
+ />
+ ) : (
+ <pre className="p-4 bg-port-bg rounded-lg text-sm text-gray-300 whitespace-pre-wrap overflow-auto max-h-96">
+ {documentContent}
+ </pre>
+ )}
+
+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 mt-4 pt-4 border-t border-port-border">
+ <p className="text-xs text-gray-500">
+ Review and edit the generated content before saving.
+ </p>
+ <button
+ onClick={saveDocument}
+ disabled={saving || !documentContent.trim()}
+ className="px-6 py-3 min-h-[44px] bg-green-600 text-white rounded-lg font-medium hover:bg-green-500 disabled:opacity-50 flex items-center justify-center gap-2"
+ >
+ {saving ? (
+ <>
+ <RefreshCw className="w-4 h-4 animate-spin" />
+ Saving...
+ </>
+ ) : (
+ <>
+ <Save size={18} />
+ Save to Digital Twin
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.js
index d9b0f6782a..eda6f6dded 100644
--- a/client/src/components/digital-twin/constants.js
+++ b/client/src/components/digital-twin/constants.js
@@ -20,7 +20,8 @@ import {
Paintbrush,
Shield,
GitBranch,
- AlertOctagon
+ AlertOctagon,
+ Fingerprint
} from 'lucide-react';
// Main navigation tabs
@@ -115,21 +116,33 @@ export const ENRICHMENT_CATEGORIES = {
label: 'Favorite Books',
description: 'Books that shaped your thinking',
icon: BookOpen,
- color: 'blue'
+ color: 'blue',
+ listBased: true,
+ itemLabel: 'Book',
+ itemPlaceholder: 'e.g., Gödel, Escher, Bach by Douglas Hofstadter',
+ notePlaceholder: 'Why this book matters to you, what it taught you...'
},
favorite_movies: {
id: 'favorite_movies',
label: 'Favorite Movies',
description: 'Films that resonate with your aesthetic and values',
icon: Film,
- color: 'red'
+ color: 'red',
+ listBased: true,
+ itemLabel: 'Movie',
+ itemPlaceholder: 'e.g., Blade Runner 2049',
+ notePlaceholder: 'What draws you to this film, memorable scenes or themes...'
},
music_taste: {
id: 'music_taste',
label: 'Music Taste',
description: 'Music as cognitive infrastructure',
icon: Music,
- color: 'green'
+ color: 'green',
+ listBased: true,
+ itemLabel: 'Album/Artist',
+ itemPlaceholder: 'e.g., OK Computer by Radiohead',
+ notePlaceholder: 'When you listen to this, how you use it (focus, energy, mood)...'
},
communication: {
id: 'communication',
@@ -193,6 +206,13 @@ export const ENRICHMENT_CATEGORIES = {
description: 'What your digital twin should never do',
icon: AlertOctagon,
color: 'rose'
+ },
+ personality_assessments: {
+ id: 'personality_assessments',
+ label: 'Personality Assessments',
+ description: 'Myers-Briggs, Big Five, Enneagram, and other personality type results',
+ icon: Fingerprint,
+ color: 'sky'
}
};
diff --git a/client/src/components/digital-twin/tabs/EnrichTab.jsx b/client/src/components/digital-twin/tabs/EnrichTab.jsx
index f577123019..2cef481ae3 100644
--- a/client/src/components/digital-twin/tabs/EnrichTab.jsx
+++ b/client/src/components/digital-twin/tabs/EnrichTab.jsx
@@ -16,6 +16,7 @@ import * as api from '../../../services/api';
import toast from 'react-hot-toast';
import { ENRICHMENT_CATEGORIES } from '../constants';
+import ListEnrichment from '../ListEnrichment';
export default function EnrichTab({ onRefresh }) {
const [categories, setCategories] = useState([]);
@@ -134,8 +135,12 @@ export default function EnrichTab({ onRefresh }) {
};
const startCategory = async (categoryId) => {
+ const config = ENRICHMENT_CATEGORIES[categoryId];
setActiveCategory(categoryId);
- await loadQuestion(categoryId);
+ // Only load question for non-list-based categories
+ if (!config?.listBased) {
+ await loadQuestion(categoryId);
+ }
};
const loadQuestion = async (categoryId) => {
@@ -187,7 +192,25 @@ export default function EnrichTab({ onRefresh }) {
);
}
- // Active enrichment session
+ // List-based enrichment (books, movies, music)
+ const activeCategoryConfig = activeCategory ? ENRICHMENT_CATEGORIES[activeCategory] : null;
+ if (activeCategory && activeCategoryConfig?.listBased) {
+ return (
+ <ListEnrichment
+ categoryId={activeCategory}
+ onBack={exitCategory}
+ onRefresh={() => {
+ loadData();
+ onRefresh?.();
+ }}
+ providers={providers}
+ selectedProvider={selectedProvider}
+ setSelectedProvider={setSelectedProvider}
+ />
+ );
+ }
+
+ // Q&A-based enrichment session
if (activeCategory && currentQuestion) {
const categoryConfig = ENRICHMENT_CATEGORIES[activeCategory];
const categoryProgress = progress?.categories?.[activeCategory];
diff --git a/client/src/components/digital-twin/tabs/OverviewTab.jsx b/client/src/components/digital-twin/tabs/OverviewTab.jsx
index e228ec2431..4e4fe04387 100644
--- a/client/src/components/digital-twin/tabs/OverviewTab.jsx
+++ b/client/src/components/digital-twin/tabs/OverviewTab.jsx
@@ -136,13 +136,13 @@ export default function OverviewTab({ status, settings, onRefresh }) {
Start Wizard
</button>
<button
- onClick={() => navigate('/soul/enrich')}
+ onClick={() => navigate('/digital-twin/enrich')}
className="px-6 py-3 min-h-[44px] 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')}
+ onClick={() => navigate('/digital-twin/documents')}
className="px-6 py-3 min-h-[44px] bg-port-card text-white rounded-lg font-medium border border-port-border hover:bg-port-border transition-colors"
>
Create Document
@@ -319,7 +319,7 @@ export default function OverviewTab({ status, settings, onRefresh }) {
</div>
{section.enrichmentCategory && (
<button
- onClick={() => navigate('/soul/enrich')}
+ onClick={() => navigate('/digital-twin/enrich')}
className="flex items-center gap-1 text-sm text-port-accent hover:text-white"
>
Add via Enrich
@@ -433,7 +433,7 @@ export default function OverviewTab({ status, settings, onRefresh }) {
<div
key={key}
className={`p-4 rounded-lg border ${config.color} cursor-pointer hover:opacity-80 transition-opacity`}
- onClick={() => navigate('/soul/documents')}
+ onClick={() => navigate('/digital-twin/documents')}
>
<div className="flex items-center gap-2 mb-2">
<Icon size={16} />
@@ -449,7 +449,7 @@ export default function OverviewTab({ status, settings, onRefresh }) {
{/* Quick Actions */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
<button
- onClick={() => navigate('/soul/test')}
+ onClick={() => navigate('/digital-twin/test')}
className="flex items-center gap-3 sm:gap-4 p-4 min-h-[72px] bg-port-card rounded-lg border border-port-border hover:border-port-accent transition-colors"
>
<div className="p-2.5 sm:p-3 rounded-lg bg-green-500/20 flex-shrink-0">
@@ -466,7 +466,7 @@ export default function OverviewTab({ status, settings, onRefresh }) {
</button>
<button
- onClick={() => navigate('/soul/enrich')}
+ onClick={() => navigate('/digital-twin/enrich')}
className="flex items-center gap-3 sm:gap-4 p-4 min-h-[72px] bg-port-card rounded-lg border border-port-border hover:border-port-accent transition-colors"
>
<div className="p-2.5 sm:p-3 rounded-lg bg-yellow-500/20 flex-shrink-0">
@@ -481,7 +481,7 @@ export default function OverviewTab({ status, settings, onRefresh }) {
</button>
<button
- onClick={() => navigate('/soul/export')}
+ onClick={() => navigate('/digital-twin/export')}
className="flex items-center gap-3 sm:gap-4 p-4 min-h-[72px] bg-port-card rounded-lg border border-port-border hover:border-port-accent transition-colors"
>
<div className="p-2.5 sm:p-3 rounded-lg bg-blue-500/20 flex-shrink-0">
@@ -516,7 +516,7 @@ export default function OverviewTab({ status, settings, onRefresh }) {
</div>
</div>
<button
- onClick={() => navigate('/soul/test')}
+ onClick={() => navigate('/digital-twin/test')}
className="px-4 py-2 min-h-[40px] text-sm text-port-accent hover:text-white transition-colors"
>
View Details
diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsx
index 6839a34f3a..7dc27f79ea 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -3,15 +3,15 @@ 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 { TABS, getHealthColor, getHealthLabel } from '../components/digital-twin/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';
+import OverviewTab from '../components/digital-twin/tabs/OverviewTab';
+import DocumentsTab from '../components/digital-twin/tabs/DocumentsTab';
+import TestTab from '../components/digital-twin/tabs/TestTab';
+import EnrichTab from '../components/digital-twin/tabs/EnrichTab';
+import ExportTab from '../components/digital-twin/tabs/ExportTab';
-export default function Soul() {
+export default function DigitalTwin() {
const { tab } = useParams();
const navigate = useNavigate();
const activeTab = tab || 'overview';
@@ -37,7 +37,7 @@ export default function Soul() {
}, [fetchData]);
const handleTabChange = (tabId) => {
- navigate(`/soul/${tabId}`);
+ navigate(`/digital-twin/${tabId}`);
};
const renderTabContent = () => {
@@ -72,8 +72,8 @@ export default function Soul() {
<div className="flex items-center gap-3">
<Heart className="w-8 h-8 text-pink-500 flex-shrink-0" />
<div>
- <h1 className="text-xl font-bold text-white">Soul</h1>
- <p className="text-sm text-gray-500">Digital twin identity scaffold</p>
+ <h1 className="text-xl font-bold text-white">Digital Twin</h1>
+ <p className="text-sm text-gray-500">Identity scaffold for AI interactions</p>
</div>
</div>
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index f4a2526162..401a938c8e 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -33,7 +33,8 @@ export const enrichmentCategoryEnum = z.enum([
'career_skills',
'non_negotiables',
'decision_heuristics',
- 'error_intolerance'
+ 'error_intolerance',
+ 'personality_assessments'
]);
// Document metadata schema
@@ -80,20 +81,22 @@ export const enrichmentProgressSchema = z.object({
questionsAnswered: z.record(enrichmentCategoryEnum, z.number().int().min(0)).optional()
});
-// Soul settings schema
-export const soulSettingsSchema = z.object({
+// Digital Twin settings schema
+export const digitalTwinSettingsSchema = z.object({
autoInjectToCoS: z.boolean().default(true),
maxContextTokens: z.number().int().min(1000).max(100000).default(4000)
});
+export const soulSettingsSchema = digitalTwinSettingsSchema; // Alias for backwards compatibility
// Full meta.json schema
-export const soulMetaSchema = z.object({
+export const digitalTwinMetaSchema = z.object({
version: z.string().default('1.0.0'),
documents: z.array(documentMetaSchema).default([]),
testHistory: z.array(testHistoryEntrySchema).default([]),
enrichment: enrichmentProgressSchema.default({ completedCategories: [], lastSession: null }),
- settings: soulSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000 })
+ settings: digitalTwinSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000 })
});
+export const soulMetaSchema = digitalTwinMetaSchema; // Alias for backwards compatibility
// --- Input schemas for API endpoints ---
@@ -182,3 +185,29 @@ export const writingAnalysisInputSchema = z.object({
providerId: z.string().min(1),
model: z.string().min(1)
});
+
+// List-based enrichment item
+export const listItemSchema = z.object({
+ title: z.string().min(1).max(500),
+ note: z.string().max(2000).optional()
+});
+
+// Analyze list input
+export const analyzeListInputSchema = z.object({
+ category: enrichmentCategoryEnum,
+ items: z.array(listItemSchema).min(1).max(50),
+ providerId: z.string().min(1),
+ model: z.string().min(1)
+});
+
+// Save list document input
+export const saveListDocumentInputSchema = z.object({
+ category: enrichmentCategoryEnum,
+ content: z.string().min(1).max(100000),
+ items: z.array(listItemSchema).min(1).max(50)
+});
+
+// Get list items input
+export const getListItemsInputSchema = z.object({
+ category: enrichmentCategoryEnum
+});
diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.js
index 26aa7b0370..bb3b61c902 100644
--- a/server/routes/digital-twin.js
+++ b/server/routes/digital-twin.js
@@ -1,7 +1,7 @@
/**
- * Soul API Routes
+ * Digital Twin API Routes
*
- * Handles all HTTP endpoints for the Soul feature:
+ * Handles all HTTP endpoints for the Digital Twin feature:
* - Document CRUD
* - Behavioral testing
* - Enrichment questionnaire
@@ -10,7 +10,7 @@
*/
import { Router } from 'express';
-import * as soulService from '../services/soul.js';
+import * as digitalTwinService from '../services/digital-twin.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validate } from '../lib/validation.js';
import {
@@ -25,8 +25,11 @@ import {
testHistoryQuerySchema,
contradictionInputSchema,
generateTestsInputSchema,
- writingAnalysisInputSchema
-} from '../lib/soulValidation.js';
+ writingAnalysisInputSchema,
+ analyzeListInputSchema,
+ saveListDocumentInputSchema,
+ getListItemsInputSchema
+} from '../lib/digitalTwinValidation.js';
const router = Router();
@@ -35,11 +38,11 @@ const router = Router();
// =============================================================================
/**
- * GET /api/soul
- * Get soul status summary
+ * GET /api/digital-twin
+ * Get digital twin status summary
*/
router.get('/', asyncHandler(async (req, res) => {
- const status = await soulService.getSoulStatus();
+ const status = await digitalTwinService.getDigitalTwinStatus();
res.json(status);
}));
@@ -48,20 +51,20 @@ router.get('/', asyncHandler(async (req, res) => {
// =============================================================================
/**
- * GET /api/soul/documents
- * List all soul documents
+ * GET /api/digital-twin/documents
+ * List all digital twin documents
*/
router.get('/documents', asyncHandler(async (req, res) => {
- const documents = await soulService.getDocuments();
+ const documents = await digitalTwinService.getDocuments();
res.json(documents);
}));
/**
- * GET /api/soul/documents/:id
+ * GET /api/digital-twin/documents/:id
* Get a single document with content
*/
router.get('/documents/:id', asyncHandler(async (req, res) => {
- const document = await soulService.getDocumentById(req.params.id);
+ const document = await digitalTwinService.getDocumentById(req.params.id);
if (!document) {
throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });
}
@@ -69,7 +72,7 @@ router.get('/documents/:id', asyncHandler(async (req, res) => {
}));
/**
- * POST /api/soul/documents
+ * POST /api/digital-twin/documents
* Create a new document
*/
router.post('/documents', asyncHandler(async (req, res) => {
@@ -82,12 +85,12 @@ router.post('/documents', asyncHandler(async (req, res) => {
});
}
- const document = await soulService.createDocument(validation.data);
+ const document = await digitalTwinService.createDocument(validation.data);
res.status(201).json(document);
}));
/**
- * PUT /api/soul/documents/:id
+ * PUT /api/digital-twin/documents/:id
* Update a document
*/
router.put('/documents/:id', asyncHandler(async (req, res) => {
@@ -100,7 +103,7 @@ router.put('/documents/:id', asyncHandler(async (req, res) => {
});
}
- const document = await soulService.updateDocument(req.params.id, validation.data);
+ const document = await digitalTwinService.updateDocument(req.params.id, validation.data);
if (!document) {
throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });
}
@@ -108,11 +111,11 @@ router.put('/documents/:id', asyncHandler(async (req, res) => {
}));
/**
- * DELETE /api/soul/documents/:id
+ * DELETE /api/digital-twin/documents/:id
* Delete a document
*/
router.delete('/documents/:id', asyncHandler(async (req, res) => {
- const deleted = await soulService.deleteDocument(req.params.id);
+ const deleted = await digitalTwinService.deleteDocument(req.params.id);
if (!deleted) {
throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });
}
@@ -124,16 +127,16 @@ router.delete('/documents/:id', asyncHandler(async (req, res) => {
// =============================================================================
/**
- * GET /api/soul/tests
+ * GET /api/digital-twin/tests
* Get the behavioral test suite (parsed from BEHAVIORAL_TEST_SUITE.md)
*/
router.get('/tests', asyncHandler(async (req, res) => {
- const tests = await soulService.parseTestSuite();
+ const tests = await digitalTwinService.parseTestSuite();
res.json(tests);
}));
/**
- * POST /api/soul/tests/run
+ * POST /api/digital-twin/tests/run
* Run behavioral tests against a single provider/model
*/
router.post('/tests/run', asyncHandler(async (req, res) => {
@@ -147,12 +150,12 @@ router.post('/tests/run', asyncHandler(async (req, res) => {
}
const { providerId, model, testIds } = validation.data;
- const result = await soulService.runTests(providerId, model, testIds);
+ const result = await digitalTwinService.runTests(providerId, model, testIds);
res.json(result);
}));
/**
- * POST /api/soul/tests/run-multi
+ * POST /api/digital-twin/tests/run-multi
* Run behavioral tests against multiple providers/models
*/
router.post('/tests/run-multi', asyncHandler(async (req, res) => {
@@ -171,7 +174,7 @@ router.post('/tests/run-multi', asyncHandler(async (req, res) => {
// 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 => ({
+ const result = await digitalTwinService.runTests(providerId, model, testIds).catch(err => ({
providerId,
model,
error: err.message
@@ -179,7 +182,7 @@ router.post('/tests/run-multi', asyncHandler(async (req, res) => {
// Emit progress via Socket.IO
if (io) {
- io.emit('soul:test-progress', { providerId, model, result });
+ io.emit('digital-twin:test-progress', { providerId, model, result });
}
return { providerId, model, ...result };
@@ -190,7 +193,7 @@ router.post('/tests/run-multi', asyncHandler(async (req, res) => {
}));
/**
- * GET /api/soul/tests/history
+ * GET /api/digital-twin/tests/history
* Get test run history
*/
router.get('/tests/history', asyncHandler(async (req, res) => {
@@ -203,7 +206,7 @@ router.get('/tests/history', asyncHandler(async (req, res) => {
});
}
- const history = await soulService.getTestHistory(validation.data.limit);
+ const history = await digitalTwinService.getTestHistory(validation.data.limit);
res.json(history);
}));
@@ -212,25 +215,25 @@ router.get('/tests/history', asyncHandler(async (req, res) => {
// =============================================================================
/**
- * GET /api/soul/enrich/categories
+ * GET /api/digital-twin/enrich/categories
* List all enrichment categories
*/
router.get('/enrich/categories', asyncHandler(async (req, res) => {
- const categories = soulService.getEnrichmentCategories();
+ const categories = digitalTwinService.getEnrichmentCategories();
res.json(categories);
}));
/**
- * GET /api/soul/enrich/progress
+ * GET /api/digital-twin/enrich/progress
* Get enrichment progress
*/
router.get('/enrich/progress', asyncHandler(async (req, res) => {
- const progress = await soulService.getEnrichmentProgress();
+ const progress = await digitalTwinService.getEnrichmentProgress();
res.json(progress);
}));
/**
- * POST /api/soul/enrich/question
+ * POST /api/digital-twin/enrich/question
* Get next question for a category
*/
router.post('/enrich/question', asyncHandler(async (req, res) => {
@@ -244,13 +247,13 @@ router.post('/enrich/question', asyncHandler(async (req, res) => {
}
const { category, providerOverride, modelOverride } = validation.data;
- const question = await soulService.generateEnrichmentQuestion(category, providerOverride, modelOverride);
+ const question = await digitalTwinService.generateEnrichmentQuestion(category, providerOverride, modelOverride);
res.json(question);
}));
/**
- * POST /api/soul/enrich/answer
- * Submit answer and update soul documents
+ * POST /api/digital-twin/enrich/answer
+ * Submit answer and update digital twin documents
*/
router.post('/enrich/answer', asyncHandler(async (req, res) => {
const validation = validate(enrichmentAnswerInputSchema, req.body);
@@ -262,25 +265,81 @@ router.post('/enrich/answer', asyncHandler(async (req, res) => {
});
}
- const result = await soulService.processEnrichmentAnswer(validation.data);
+ const result = await digitalTwinService.processEnrichmentAnswer(validation.data);
res.json(result);
}));
+/**
+ * POST /api/digital-twin/enrich/analyze-list
+ * Analyze a list of items (books, movies, music) and generate document content
+ */
+router.post('/enrich/analyze-list', asyncHandler(async (req, res) => {
+ const validation = validate(analyzeListInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { category, items, providerId, model } = validation.data;
+ const result = await digitalTwinService.analyzeEnrichmentList(category, items, providerId, model);
+ res.json(result);
+}));
+
+/**
+ * POST /api/digital-twin/enrich/save-list
+ * Save analyzed list content to document
+ */
+router.post('/enrich/save-list', asyncHandler(async (req, res) => {
+ const validation = validate(saveListDocumentInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const { category, content, items } = validation.data;
+ const result = await digitalTwinService.saveEnrichmentListDocument(category, content, items);
+ res.json(result);
+}));
+
+/**
+ * GET /api/digital-twin/enrich/list-items/:category
+ * Get previously saved list items for a category
+ */
+router.get('/enrich/list-items/:category', asyncHandler(async (req, res) => {
+ const validation = validate(getListItemsInputSchema, { category: req.params.category });
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const items = await digitalTwinService.getEnrichmentListItems(validation.data.category);
+ res.json(items);
+}));
+
// =============================================================================
// EXPORT
// =============================================================================
/**
- * GET /api/soul/export/formats
+ * GET /api/digital-twin/export/formats
* List available export formats
*/
router.get('/export/formats', asyncHandler(async (req, res) => {
- const formats = soulService.getExportFormats();
+ const formats = digitalTwinService.getExportFormats();
res.json(formats);
}));
/**
- * POST /api/soul/export
+ * POST /api/digital-twin/export
* Export soul in specified format
*/
router.post('/export', asyncHandler(async (req, res) => {
@@ -294,7 +353,7 @@ router.post('/export', asyncHandler(async (req, res) => {
}
const { format, documentIds, includeDisabled } = validation.data;
- const exported = await soulService.exportSoul(format, documentIds, includeDisabled);
+ const exported = await digitalTwinService.exportDigitalTwin(format, documentIds, includeDisabled);
res.json(exported);
}));
@@ -303,17 +362,17 @@ router.post('/export', asyncHandler(async (req, res) => {
// =============================================================================
/**
- * GET /api/soul/settings
- * Get soul settings
+ * GET /api/digital-twin/settings
+ * Get digital twin settings
*/
router.get('/settings', asyncHandler(async (req, res) => {
- const meta = await soulService.loadMeta();
+ const meta = await digitalTwinService.loadMeta();
res.json(meta.settings);
}));
/**
- * PUT /api/soul/settings
- * Update soul settings
+ * PUT /api/digital-twin/settings
+ * Update digital twin settings
*/
router.put('/settings', asyncHandler(async (req, res) => {
const validation = validate(settingsUpdateInputSchema, req.body);
@@ -325,7 +384,7 @@ router.put('/settings', asyncHandler(async (req, res) => {
});
}
- const settings = await soulService.updateSettings(validation.data);
+ const settings = await digitalTwinService.updateSettings(validation.data);
res.json(settings);
}));
@@ -334,17 +393,17 @@ router.put('/settings', asyncHandler(async (req, res) => {
// =============================================================================
/**
- * GET /api/soul/validate/completeness
- * Check soul document completeness
+ * GET /api/digital-twin/validate/completeness
+ * Check digital twin document completeness
*/
router.get('/validate/completeness', asyncHandler(async (req, res) => {
- const result = await soulService.validateCompleteness();
+ const result = await digitalTwinService.validateCompleteness();
res.json(result);
}));
/**
- * POST /api/soul/validate/contradictions
- * Detect contradictions in soul documents using AI
+ * POST /api/digital-twin/validate/contradictions
+ * Detect contradictions in digital twin documents using AI
*/
router.post('/validate/contradictions', asyncHandler(async (req, res) => {
const validation = validate(contradictionInputSchema, req.body);
@@ -357,12 +416,12 @@ router.post('/validate/contradictions', asyncHandler(async (req, res) => {
}
const { providerId, model } = validation.data;
- const result = await soulService.detectContradictions(providerId, model);
+ const result = await digitalTwinService.detectContradictions(providerId, model);
res.json(result);
}));
/**
- * POST /api/soul/tests/generate
+ * POST /api/digital-twin/tests/generate
* Generate behavioral tests from soul content
*/
router.post('/tests/generate', asyncHandler(async (req, res) => {
@@ -376,12 +435,12 @@ router.post('/tests/generate', asyncHandler(async (req, res) => {
}
const { providerId, model } = validation.data;
- const result = await soulService.generateDynamicTests(providerId, model);
+ const result = await digitalTwinService.generateDynamicTests(providerId, model);
res.json(result);
}));
/**
- * POST /api/soul/analyze-writing
+ * POST /api/digital-twin/analyze-writing
* Analyze writing samples to extract communication patterns
*/
router.post('/analyze-writing', asyncHandler(async (req, res) => {
@@ -395,7 +454,7 @@ router.post('/analyze-writing', asyncHandler(async (req, res) => {
}
const { samples, providerId, model } = validation.data;
- const result = await soulService.analyzeWritingSamples(samples, providerId, model);
+ const result = await digitalTwinService.analyzeWritingSamples(samples, providerId, model);
res.json(result);
}));
diff --git a/server/services/digital-twin.js b/server/services/digital-twin.js
index ffecd90f00..ee44b88cf2 100644
--- a/server/services/digital-twin.js
+++ b/server/services/digital-twin.js
@@ -1,12 +1,12 @@
/**
- * Soul Service
+ * Digital Twin Service
*
- * Core business logic for the Soul feature:
- * - Document CRUD (manage soul markdown files)
+ * Core business logic for the Digital Twin feature:
+ * - Document CRUD (manage digital twin markdown files)
* - Behavioral testing against LLMs
* - Enrichment questionnaire system
* - Export for external LLM use
- * - CoS integration (soul context injection)
+ * - CoS integration (digital twin context injection)
*/
import { readFile, writeFile, unlink, readdir, mkdir, stat } from 'fs/promises';
@@ -18,18 +18,19 @@ import EventEmitter from 'events';
import { getActiveProvider, getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
import {
- soulMetaSchema,
+ digitalTwinMetaSchema,
documentMetaSchema,
testHistoryEntrySchema
-} from '../lib/soulValidation.js';
+} from '../lib/digitalTwinValidation.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');
+const DIGITAL_TWIN_DIR = join(__dirname, '../../data/digital-twin');
+const META_FILE = join(DIGITAL_TWIN_DIR, 'meta.json');
-// Event emitter for soul data changes
-export const soulEvents = new EventEmitter();
+// Event emitter for digital twin data changes
+export const digitalTwinEvents = new EventEmitter();
+export const soulEvents = digitalTwinEvents; // Alias for backwards compatibility
// In-memory cache
const cache = {
@@ -66,6 +67,11 @@ export const ENRICHMENT_CATEGORIES = {
description: 'Books that shaped your thinking',
targetDoc: 'BOOKS.md',
targetCategory: 'entertainment',
+ listBased: true,
+ itemLabel: 'Book',
+ itemPlaceholder: 'e.g., Gödel, Escher, Bach by Douglas Hofstadter',
+ notePlaceholder: 'Why this book matters to you, what it taught you...',
+ analyzePrompt: 'Analyze these book choices to understand the reader\'s intellectual interests, values, and worldview.',
questions: [
'What book fundamentally changed how you see the world?',
'Which book do you find yourself re-reading or recommending most?',
@@ -77,6 +83,11 @@ export const ENRICHMENT_CATEGORIES = {
description: 'Films that resonate with your aesthetic and values',
targetDoc: 'MOVIES.md',
targetCategory: 'entertainment',
+ listBased: true,
+ itemLabel: 'Movie',
+ itemPlaceholder: 'e.g., Blade Runner 2049',
+ notePlaceholder: 'What draws you to this film, memorable scenes or themes...',
+ analyzePrompt: 'Analyze these film choices to understand the person\'s aesthetic preferences, emotional resonance patterns, and values.',
questions: [
'What film captures your aesthetic sensibility?',
'Which movie do you quote or reference most often?',
@@ -88,6 +99,11 @@ export const ENRICHMENT_CATEGORIES = {
description: 'Music as cognitive infrastructure',
targetDoc: 'MUSIC.md',
targetCategory: 'audio',
+ listBased: true,
+ itemLabel: 'Album/Artist',
+ itemPlaceholder: 'e.g., OK Computer by Radiohead',
+ notePlaceholder: 'When you listen to this, how you use it (focus, energy, mood)...',
+ analyzePrompt: 'Analyze these music choices to understand how this person uses music for cognitive and emotional regulation.',
questions: [
'What album do you use for deep focus work?',
'What music captures your emotional baseline?',
@@ -192,6 +208,17 @@ export const ENRICHMENT_CATEGORIES = {
'What should your digital twin never do when responding to you?',
'What type of "help" actually makes things worse for you?'
]
+ },
+ personality_assessments: {
+ label: 'Personality Assessments',
+ description: 'Personality type results from assessments like Myers-Briggs, Big Five, DISC, Enneagram, etc.',
+ targetDoc: 'PERSONALITY.md',
+ targetCategory: 'core',
+ questions: [
+ 'What is your Myers-Briggs type (e.g., INTJ, ENFP)? If you test differently at different times, list all results.',
+ 'If you know your Big Five (OCEAN) scores, what are they? High/low on Openness, Conscientiousness, Extraversion, Agreeableness, Neuroticism?',
+ 'Have you taken other personality assessments (Enneagram, DISC, StrengthsFinder, etc.)? Share those results.'
+ ]
}
};
@@ -208,9 +235,9 @@ function now() {
}
async function ensureSoulDir() {
- if (!existsSync(SOUL_DIR)) {
- await mkdir(SOUL_DIR, { recursive: true });
- console.log(`🧬 Created soul data directory: ${SOUL_DIR}`);
+ if (!existsSync(DIGITAL_TWIN_DIR)) {
+ await mkdir(DIGITAL_TWIN_DIR, { recursive: true });
+ console.log(`🧬 Created soul data directory: ${DIGITAL_TWIN_DIR}`);
}
}
@@ -234,7 +261,7 @@ export async function loadMeta() {
const content = await readFile(META_FILE, 'utf-8');
const parsed = JSON.parse(content);
- const validated = soulMetaSchema.safeParse(parsed);
+ const validated = digitalTwinMetaSchema.safeParse(parsed);
cache.meta.data = validated.success ? validated.data : { ...DEFAULT_META, ...parsed };
cache.meta.timestamp = Date.now();
@@ -244,11 +271,11 @@ export async function loadMeta() {
async function buildInitialMeta() {
const meta = { ...DEFAULT_META };
- const files = await readdir(SOUL_DIR).catch(() => []);
+ const files = await readdir(DIGITAL_TWIN_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 content = await readFile(join(DIGITAL_TWIN_DIR, file), 'utf-8').catch(() => '');
const title = extractTitle(content) || file.replace('.md', '');
const category = inferCategory(file);
const version = extractVersion(content);
@@ -357,7 +384,7 @@ export async function getDocuments() {
const documents = [];
for (const doc of meta.documents) {
- const filePath = join(SOUL_DIR, doc.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
const exists = existsSync(filePath);
if (exists) {
@@ -379,7 +406,7 @@ export async function getDocumentById(id) {
if (!docMeta) return null;
- const filePath = join(SOUL_DIR, docMeta.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, docMeta.filename);
if (!existsSync(filePath)) return null;
const content = await readFile(filePath, 'utf-8');
@@ -397,7 +424,7 @@ export async function createDocument(data) {
await ensureSoulDir();
const meta = await loadMeta();
- const filePath = join(SOUL_DIR, data.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, data.filename);
// Check if file already exists
if (existsSync(filePath)) {
@@ -434,7 +461,7 @@ export async function updateDocument(id, updates) {
if (docIndex === -1) return null;
const docMeta = meta.documents[docIndex];
- const filePath = join(SOUL_DIR, docMeta.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, docMeta.filename);
// Update file content if provided
if (updates.content) {
@@ -465,7 +492,7 @@ export async function deleteDocument(id) {
if (docIndex === -1) return false;
const docMeta = meta.documents[docIndex];
- const filePath = join(SOUL_DIR, docMeta.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, docMeta.filename);
// Delete file
if (existsSync(filePath)) {
@@ -489,7 +516,7 @@ export async function parseTestSuite() {
return cache.tests.data;
}
- const testFile = join(SOUL_DIR, 'BEHAVIORAL_TEST_SUITE.md');
+ const testFile = join(DIGITAL_TWIN_DIR, 'BEHAVIORAL_TEST_SUITE.md');
if (!existsSync(testFile)) {
return [];
}
@@ -724,7 +751,12 @@ export function getEnrichmentCategories() {
label: config.label,
description: config.description,
targetDoc: config.targetDoc,
- sampleQuestions: config.questions.length
+ sampleQuestions: config.questions.length,
+ // List-based category config
+ listBased: config.listBased || false,
+ itemLabel: config.itemLabel,
+ itemPlaceholder: config.itemPlaceholder,
+ notePlaceholder: config.notePlaceholder
}));
}
@@ -860,7 +892,7 @@ export async function processEnrichmentAnswer(data) {
}
// Append to target document
- const targetPath = join(SOUL_DIR, config.targetDoc);
+ const targetPath = join(DIGITAL_TWIN_DIR, config.targetDoc);
let existingContent = '';
if (existsSync(targetPath)) {
@@ -934,6 +966,197 @@ export async function getEnrichmentProgress() {
};
}
+/**
+ * Analyze a list of items (books, movies, music) and generate document content
+ * @param {string} category - The enrichment category
+ * @param {Array} items - Array of { title, note } objects
+ * @param {string} providerId - Provider to use for analysis
+ * @param {string} model - Model to use
+ * @returns {Object} - { analysis, suggestedContent, items }
+ */
+export async function analyzeEnrichmentList(category, items, providerId, model) {
+ const config = ENRICHMENT_CATEGORIES[category];
+ if (!config) {
+ throw new Error(`Unknown enrichment category: ${category}`);
+ }
+
+ if (!config.listBased) {
+ throw new Error(`Category ${category} does not support list-based enrichment`);
+ }
+
+ if (!items || items.length === 0) {
+ throw new Error('No items provided');
+ }
+
+ const provider = await getProviderById(providerId);
+ if (!provider || !provider.enabled) {
+ throw new Error('Provider not found or disabled');
+ }
+
+ // Format items for the prompt
+ const itemsList = items.map((item, i) => {
+ let entry = `${i + 1}. ${item.title}`;
+ if (item.note) {
+ entry += `\n User's note: ${item.note}`;
+ }
+ return entry;
+ }).join('\n\n');
+
+ // Build the analysis prompt
+ const prompt = `You are analyzing someone's ${config.label.toLowerCase()} to understand their personality, values, and preferences.
+
+${config.analyzePrompt}
+
+## Items provided:
+
+${itemsList}
+
+## Your task:
+
+1. **Analysis**: For each item, briefly note what it might reveal about the person (themes, values, intellectual interests, emotional patterns).
+
+2. **Patterns**: Identify 3-5 overarching patterns or themes across all choices.
+
+3. **Personality Insights**: What does this collection suggest about the person's:
+ - Intellectual interests and curiosities
+ - Values and worldview
+ - Aesthetic preferences
+ - Emotional landscape
+
+4. **Generate Document**: Create a markdown document for ${config.targetDoc} that captures these insights in a format useful for an AI digital twin.
+
+Respond in JSON format:
+\`\`\`json
+{
+ "itemAnalysis": [
+ { "title": "...", "insights": "..." }
+ ],
+ "patterns": ["pattern 1", "pattern 2", ...],
+ "personalityInsights": {
+ "intellectualInterests": "...",
+ "valuesWorldview": "...",
+ "aestheticPreferences": "...",
+ "emotionalLandscape": "..."
+ },
+ "suggestedDocument": "# ${config.label}\\n\\n..."
+}
+\`\`\``;
+
+ if (provider.type !== 'api') {
+ throw new Error('List analysis requires an API provider');
+ }
+
+ 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) {
+ throw new Error(`API error: ${response.status}`);
+ }
+
+ const data = await response.json();
+ const responseText = data.choices?.[0]?.message?.content || '';
+
+ // Parse the JSON response
+ const jsonMatch = responseText.match(/```json\s*([\s\S]*?)\s*```/);
+ if (jsonMatch) {
+ const parsed = JSON.parse(jsonMatch[1]);
+ return {
+ category,
+ items,
+ itemAnalysis: parsed.itemAnalysis || [],
+ patterns: parsed.patterns || [],
+ personalityInsights: parsed.personalityInsights || {},
+ suggestedDocument: parsed.suggestedDocument || '',
+ targetDoc: config.targetDoc,
+ targetCategory: config.targetCategory
+ };
+ }
+
+ // Fallback if JSON parsing fails
+ return {
+ category,
+ items,
+ rawResponse: responseText,
+ suggestedDocument: responseText,
+ targetDoc: config.targetDoc,
+ targetCategory: config.targetCategory
+ };
+}
+
+/**
+ * Save analyzed list content to document
+ */
+export async function saveEnrichmentListDocument(category, content, items) {
+ const config = ENRICHMENT_CATEGORIES[category];
+ if (!config) {
+ throw new Error(`Unknown enrichment category: ${category}`);
+ }
+
+ await ensureSoulDir();
+
+ const targetPath = join(DIGITAL_TWIN_DIR, config.targetDoc);
+ await writeFile(targetPath, content);
+
+ // Update meta
+ const meta = await loadMeta();
+
+ // Mark as completed since they provided a full list
+ if (!meta.enrichment.completedCategories.includes(category)) {
+ meta.enrichment.completedCategories.push(category);
+ }
+
+ // Store the list items for future reference/editing
+ if (!meta.enrichment.listItems) {
+ meta.enrichment.listItems = {};
+ }
+ meta.enrichment.listItems[category] = items;
+ meta.enrichment.lastSession = now();
+
+ // 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(`🧬 Saved list-based enrichment for ${category} (${items.length} items)`);
+
+ return {
+ category,
+ targetDoc: config.targetDoc,
+ itemCount: items.length
+ };
+}
+
+/**
+ * Get previously saved list items for a category
+ */
+export async function getEnrichmentListItems(category) {
+ const meta = await loadMeta();
+ return meta.enrichment.listItems?.[category] || [];
+}
+
// =============================================================================
// EXPORT
// =============================================================================
@@ -947,7 +1170,7 @@ export function getExportFormats() {
];
}
-export async function exportSoul(format, documentIds = null, includeDisabled = false) {
+export async function exportDigitalTwin(format, documentIds = null, includeDisabled = false) {
const meta = await loadMeta();
let docs = meta.documents;
@@ -970,7 +1193,7 @@ export async function exportSoul(format, documentIds = null, includeDisabled = f
// Load content for each document
const documentsWithContent = [];
for (const doc of docs) {
- const filePath = join(SOUL_DIR, doc.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
if (existsSync(filePath)) {
const content = await readFile(filePath, 'utf-8');
documentsWithContent.push({ ...doc, content });
@@ -1052,6 +1275,7 @@ function exportAsJson(docs) {
tokenEstimate: Math.ceil(jsonString.length / 4)
};
}
+export const exportSoul = exportDigitalTwin; // Alias for backwards compatibility
function exportAsIndividual(docs) {
return {
@@ -1071,7 +1295,7 @@ function exportAsIndividual(docs) {
// COS INTEGRATION
// =============================================================================
-export async function getSoulForPrompt(options = {}) {
+export async function getDigitalTwinForPrompt(options = {}) {
const { maxTokens = 4000 } = options;
const meta = await loadMeta();
@@ -1095,7 +1319,7 @@ export async function getSoulForPrompt(options = {}) {
const maxChars = maxTokens * 4; // Rough char-to-token estimate
for (const doc of docs) {
- const filePath = join(SOUL_DIR, doc.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
if (!existsSync(filePath)) continue;
const content = await readFile(filePath, 'utf-8');
@@ -1115,12 +1339,13 @@ export async function getSoulForPrompt(options = {}) {
return output.trim();
}
+export const getSoulForPrompt = getDigitalTwinForPrompt; // Alias for backwards compatibility
// =============================================================================
// STATUS & SUMMARY
// =============================================================================
-export async function getSoulStatus() {
+export async function getDigitalTwinStatus() {
const meta = await loadMeta();
const documents = await getDocuments();
const testHistory = meta.testHistory.slice(0, 5);
@@ -1151,12 +1376,13 @@ export async function getSoulStatus() {
settings: meta.settings
};
}
+export const getSoulStatus = getDigitalTwinStatus; // Alias for backwards compatibility
// =============================================================================
// VALIDATION & ANALYSIS
// =============================================================================
-// Required sections for a complete soul
+// Required sections for a complete digital twin
const REQUIRED_SECTIONS = [
{
id: 'identity',
@@ -1215,7 +1441,7 @@ export async function validateCompleteness() {
// Load content for all enabled documents
const contents = [];
for (const doc of enabledDocs) {
- const filePath = join(SOUL_DIR, doc.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
if (existsSync(filePath)) {
const content = await readFile(filePath, 'utf-8');
contents.push({ doc, content: content.toLowerCase() });
@@ -1270,7 +1496,7 @@ export async function detectContradictions(providerId, model) {
// Load all document contents
let combinedContent = '';
for (const doc of enabledDocs) {
- const filePath = join(SOUL_DIR, doc.filename);
+ const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
if (existsSync(filePath)) {
const content = await readFile(filePath, 'utf-8');
combinedContent += `\n\n## Document: ${doc.filename}\n\n${content}`;