Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(digital-twin): add external data integration (M34 Phase 4)
Adam Eivycb9c9b06b947
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex 8ae0cf4766..6c305048b5 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -101,6 +101,18 @@ This release introduces a structured changelog documentation system for creating- **Local Fallback**: Heuristic-based confidence calculation when AI provider is unavailable- **Overview Tab Integration**: New components integrated into Digital Twin Overview tab for at-a-glance personality insights+### Digital Twin - External Data Integration (M34 Phase 4)+- **Import Tab**: New dedicated tab for importing personal data from external services+- **Goodreads CSV Import**: Parse Goodreads library exports to extract reading history, favorites, and shelf data for personality analysis+- **Spotify JSON Import**: Import Spotify extended streaming history and library data to capture music preferences and listening patterns+- **Letterboxd CSV Import**: Parse Letterboxd exports for film ratings, reviews, and watchlists+- **iCal Import**: Parse calendar files (.ics) to understand routines, priorities, and time allocation patterns+- **AI-Powered Analysis**: Uses `twin-import-analyzer.md` prompt template to extract personality insights from imported data+- **Document Generation**: Analyzed imports can be saved directly as digital twin documents with appropriate categorization+- **Provider Selection**: Choose AI provider/model for analysis with multi-tier support+- **Validation Schemas**: New Zod schemas for import sources and analysis results+- **API Endpoints**: New `/api/digital-twin/import/sources`, `/api/digital-twin/import/analyze`, and `/api/digital-twin/import/save` endpoints+### AI Provider Usage Limit Handling & Fallback- **Usage Limit Detection**: Agents now detect provider usage limit errors (e.g., "You've hit your usage limit. Upgrade to Pro or try again in 1 day 1 hour 33 minutes") and mark providers as temporarily unavailable- **Provider Status Tracking**: New `providerStatus.js` service tracks provider availability, usage limits, and estimated recovery times with persistence across server restartsdiff --git a/PLAN.md b/PLAN.mdindex da741728ca..da0c984bc6 100644--- a/PLAN.md+++ b/PLAN.md@@ -844,26 +844,30 @@ feedback: [----### Implementation Priority--| Phase | Priority | Complexity | Impact |-|-------|----------|------------|--------|-| P1: Quantitative Modeling | HIGH | Medium | High - enables all other phases |-| P2: Confidence Scoring | HIGH | Low | High - guides enrichment |-| P3: Feedback Loop | HIGH | Medium | Very High - enables learning |-| P4: External Integration | MEDIUM | High | Medium - convenience |-| P5: Multi-Modal | LOW | Very High | Medium - nice to have |-| P6: Advanced Testing | MEDIUM | Medium | High - validation quality |-| P7: Personas | LOW | Medium | Medium - power users |--### Recommended Starting Point--**Phase 1.1 + 2.1 + 2.3** as single implementation:-1. Add Big Five trait analysis from existing documents-2. Add confidence scoring per dimension-3. Add gap recommendations in UI--This provides immediate value by making the enrichment process more guided and measurable.+### Implementation Status++| Phase | Status | Complexity | Impact |+|-------|--------|------------|--------|+| P1: Quantitative Modeling | ✅ COMPLETE | Medium | High - enables all other phases |+| P2: Confidence Scoring | ✅ COMPLETE | Low | High - guides enrichment |+| P3: Feedback Loop | 🔲 Planned | Medium | Very High - enables learning |+| P4: External Integration | ✅ COMPLETE | High | Medium - convenience |+| P5: Multi-Modal | 🔲 Planned | Very High | Medium - nice to have |+| P6: Advanced Testing | 🔲 Planned | Medium | High - validation quality |+| P7: Personas | 🔲 Planned | Medium | Medium - power users |++### Completed: Phase 1 & 2 (2026-01-21)++Implemented quantitative personality modeling and confidence scoring:+- Big Five trait extraction via AI analysis+- Values hierarchy with conflict detection+- Communication profile quantification+- Per-dimension confidence scoring+- Gap recommendations for low-confidence areas+- PersonalityMap radar chart component+- ConfidenceGauge visualization component+- GapRecommendations prioritized list component+- API endpoints: `/traits`, `/traits/analyze`, `/confidence`, `/confidence/calculate`, `/gaps`### Success Metricsdiff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.jsindex eda6f6dded..ca05fae132 100644--- a/client/src/components/digital-twin/constants.js+++ b/client/src/components/digital-twin/constants.js@@ -4,6 +4,7 @@ import {CheckCircle,Sparkles,Download,+ Upload,Settings,BookOpen,Film,@@ -30,6 +31,7 @@ export const TABS = [{ id: 'documents', label: 'Documents', icon: FileText },{ id: 'test', label: 'Test', icon: CheckCircle },{ id: 'enrich', label: 'Enrich', icon: Sparkles },+ { id: 'import', label: 'Import', icon: Upload },{ id: 'export', label: 'Export', icon: Download }];diff --git a/client/src/components/digital-twin/tabs/ImportTab.jsx b/client/src/components/digital-twin/tabs/ImportTab.jsxnew file mode 100644index 0000000000..ac54b6f915--- /dev/null+++ b/client/src/components/digital-twin/tabs/ImportTab.jsx@@ -0,0 +1,486 @@+import { useState, useEffect } from 'react';+import {+ Upload,+ BookOpen,+ Music,+ Film,+ Calendar,+ RefreshCw,+ Check,+ AlertCircle,+ FileText,+ ChevronRight,+ ExternalLink,+ Save,+ Trash2+} from 'lucide-react';+import * as api from '../../../services/api';+import toast from 'react-hot-toast';++const SOURCE_ICONS = {+ goodreads: BookOpen,+ spotify: Music,+ letterboxd: Film,+ ical: Calendar+};++const SOURCE_COLORS = {+ goodreads: 'text-amber-400 bg-amber-500/20',+ spotify: 'text-green-400 bg-green-500/20',+ letterboxd: 'text-orange-400 bg-orange-500/20',+ ical: 'text-blue-400 bg-blue-500/20'+};++export default function ImportTab() {+ const [sources, setSources] = useState([]);+ const [providers, setProviders] = useState([]);+ const [selectedSource, setSelectedSource] = useState(null);+ const [selectedProvider, setSelectedProvider] = useState(null);+ const [fileContent, setFileContent] = useState('');+ const [analyzing, setAnalyzing] = useState(false);+ const [analysisResult, setAnalysisResult] = useState(null);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ loadSources();+ loadProviders();+ }, []);++ const loadSources = async () => {+ const data = await api.getDigitalTwinImportSources().catch(() => ({ sources: [] }));+ setSources(data.sources || []);+ };++ 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 handleFileUpload = (e) => {+ const file = e.target.files?.[0];+ if (!file) return;++ const reader = new FileReader();+ reader.onload = (event) => {+ setFileContent(event.target.result);+ setAnalysisResult(null);+ };+ reader.readAsText(file);+ };++ const handleAnalyze = async () => {+ if (!selectedSource || !fileContent || !selectedProvider) {+ toast.error('Please select a source, upload a file, and choose a provider');+ return;+ }++ setAnalyzing(true);+ setAnalysisResult(null);++ const result = await api.analyzeDigitalTwinImport(+ selectedSource.id,+ fileContent,+ selectedProvider.providerId,+ selectedProvider.model+ ).catch(e => ({ error: e.message }));++ if (result.error) {+ toast.error(result.error);+ } else {+ setAnalysisResult(result);+ toast.success(`Analyzed ${result.itemCount} items from ${selectedSource.name}`);+ }++ setAnalyzing(false);+ };++ const handleSaveDocument = async (suggestedDoc) => {+ setSaving(true);++ const result = await api.saveDigitalTwinImport(+ selectedSource.id,+ suggestedDoc+ ).catch(e => ({ error: e.message }));++ if (result.error) {+ toast.error(result.error);+ } else {+ toast.success(`Document "${suggestedDoc.title}" saved successfully`);+ // Remove saved document from suggestions+ setAnalysisResult(prev => ({+ ...prev,+ suggestedDocuments: prev.suggestedDocuments?.filter(d => d.filename !== suggestedDoc.filename)+ }));+ }++ setSaving(false);+ };++ const handleReset = () => {+ setSelectedSource(null);+ setFileContent('');+ setAnalysisResult(null);+ };++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="bg-port-card rounded-lg border border-port-border p-6">+ <div className="flex items-center gap-3 mb-4">+ <Upload className="w-6 h-6 text-purple-400" />+ <h2 className="text-xl font-semibold text-white">Import External Data</h2>+ </div>+ <p className="text-gray-400">+ Import data from external services to automatically extract personality insights.+ Your data is processed locally and only the personality inferences are stored.+ </p>+ </div>++ {/* Source Selection */}+ {!selectedSource && (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ {sources.map(source => {+ const Icon = SOURCE_ICONS[source.id] || FileText;+ const colorClass = SOURCE_COLORS[source.id] || 'text-gray-400 bg-gray-500/20';++ return (+ <button+ key={source.id}+ onClick={() => setSelectedSource(source)}+ className="p-6 bg-port-card rounded-lg border border-port-border hover:border-port-accent transition-colors text-left"+ >+ <div className="flex items-start gap-4">+ <div className={`p-3 rounded-lg ${colorClass}`}>+ <Icon className="w-6 h-6" />+ </div>+ <div className="flex-1">+ <div className="flex items-center justify-between">+ <h3 className="font-semibold text-white">{source.name}</h3>+ <span className="text-xs text-gray-500 bg-port-bg px-2 py-1 rounded">+ {source.format}+ </span>+ </div>+ <p className="text-sm text-gray-400 mt-1">{source.description}</p>+ </div>+ </div>+ </button>+ );+ })}+ </div>+ )}++ {/* Selected Source - Upload & Analyze */}+ {selectedSource && !analysisResult && (+ <div className="bg-port-card rounded-lg border border-port-border p-6">+ <div className="flex items-center justify-between mb-6">+ <div className="flex items-center gap-3">+ {(() => {+ const Icon = SOURCE_ICONS[selectedSource.id] || FileText;+ const colorClass = SOURCE_COLORS[selectedSource.id] || 'text-gray-400 bg-gray-500/20';+ return (+ <div className={`p-2 rounded-lg ${colorClass}`}>+ <Icon className="w-5 h-5" />+ </div>+ );+ })()}+ <div>+ <h3 className="font-semibold text-white">{selectedSource.name}</h3>+ <span className="text-xs text-gray-500">{selectedSource.format} file</span>+ </div>+ </div>+ <button+ onClick={handleReset}+ className="text-sm text-gray-400 hover:text-white transition-colors"+ >+ Change Source+ </button>+ </div>++ {/* Instructions */}+ <div className="mb-6 p-4 bg-port-bg rounded-lg border border-port-border">+ <h4 className="text-sm font-medium text-white mb-2">How to export your data</h4>+ <p className="text-sm text-gray-400">{selectedSource.instructions}</p>+ </div>++ {/* File Upload */}+ <div className="mb-6">+ <label className="block text-sm font-medium text-gray-400 mb-2">+ Upload {selectedSource.format} File+ </label>+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">+ <label className="flex-1 flex items-center justify-center px-4 py-8 border-2 border-dashed border-port-border rounded-lg cursor-pointer hover:border-port-accent transition-colors">+ <input+ type="file"+ accept={selectedSource.format === 'CSV' ? '.csv' : selectedSource.format === 'JSON' ? '.json' : '.ics,.ical'}+ onChange={handleFileUpload}+ className="hidden"+ />+ <div className="text-center">+ <Upload className="w-8 h-8 text-gray-500 mx-auto mb-2" />+ <span className="text-sm text-gray-400">+ {fileContent ? 'File loaded - click to change' : `Click to upload ${selectedSource.format} file`}+ </span>+ </div>+ </label>+ </div>+ {fileContent && (+ <div className="mt-2 flex items-center gap-2 text-sm text-green-400">+ <Check className="w-4 h-4" />+ File loaded ({Math.round(fileContent.length / 1024)} KB)+ </div>+ )}+ </div>++ {/* Provider Selection */}+ <div className="mb-6">+ <label className="block text-sm font-medium text-gray-400 mb-2">+ Analysis Provider+ </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 bg-port-bg border border-port-border rounded-lg text-white"+ >+ {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>++ {/* Analyze Button */}+ <button+ onClick={handleAnalyze}+ disabled={!fileContent || analyzing}+ className="w-full 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 flex items-center justify-center gap-2"+ >+ {analyzing ? (+ <>+ <RefreshCw className="w-5 h-5 animate-spin" />+ Analyzing...+ </>+ ) : (+ <>+ <Upload className="w-5 h-5" />+ Analyze Data+ </>+ )}+ </button>+ </div>+ )}++ {/* Analysis Results */}+ {analysisResult && (+ <div className="space-y-6">+ {/* Summary */}+ <div className="bg-port-card rounded-lg border border-port-border p-6">+ <div className="flex items-center justify-between mb-4">+ <h3 className="text-lg font-semibold text-white flex items-center gap-2">+ <Check className="w-5 h-5 text-green-400" />+ Analysis Complete+ </h3>+ <button+ onClick={handleReset}+ className="text-sm text-gray-400 hover:text-white flex items-center gap-1"+ >+ <Trash2 className="w-4 h-4" />+ Start Over+ </button>+ </div>++ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-4">+ <div className="text-center p-3 bg-port-bg rounded-lg">+ <div className="text-2xl font-bold text-white">{analysisResult.itemCount}</div>+ <div className="text-xs text-gray-500">Items Analyzed</div>+ </div>+ <div className="text-center p-3 bg-port-bg rounded-lg">+ <div className="text-2xl font-bold text-white">+ {analysisResult.insights?.patterns?.length || 0}+ </div>+ <div className="text-xs text-gray-500">Patterns Found</div>+ </div>+ <div className="text-center p-3 bg-port-bg rounded-lg">+ <div className="text-2xl font-bold text-white">+ {analysisResult.insights?.personalityInferences?.values?.length || 0}+ </div>+ <div className="text-xs text-gray-500">Values Identified</div>+ </div>+ <div className="text-center p-3 bg-port-bg rounded-lg">+ <div className="text-2xl font-bold text-white">+ {analysisResult.suggestedDocuments?.length || 0}+ </div>+ <div className="text-xs text-gray-500">Documents Suggested</div>+ </div>+ </div>++ {analysisResult.rawSummary && (+ <p className="text-gray-400 border-t border-port-border pt-4">+ {analysisResult.rawSummary}+ </p>+ )}+ </div>++ {/* Personality Inferences */}+ {analysisResult.insights?.personalityInferences && (+ <div className="bg-port-card rounded-lg border border-port-border p-6">+ <h3 className="text-lg font-semibold text-white mb-4">Personality Inferences</h3>++ {/* Big Five */}+ {analysisResult.insights.personalityInferences.bigFive && (+ <div className="mb-6">+ <h4 className="text-sm font-medium text-gray-400 mb-3">Big Five Traits</h4>+ <div className="grid grid-cols-5 gap-2">+ {Object.entries(analysisResult.insights.personalityInferences.bigFive).map(([trait, score]) => {+ const labels = { O: 'Open', C: 'Consc', E: 'Extra', A: 'Agree', N: 'Neuro' };+ return (+ <div key={trait} className="text-center">+ <div className="text-xs text-gray-500 mb-1">{labels[trait] || trait}</div>+ <div className="h-16 bg-port-bg rounded-lg relative overflow-hidden">+ <div+ className="absolute bottom-0 left-0 right-0 bg-port-accent/50"+ style={{ height: `${score * 100}%` }}+ />+ <div className="absolute inset-0 flex items-center justify-center">+ <span className="text-sm font-medium text-white">+ {Math.round(score * 100)}%+ </span>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Values & Interests */}+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ {analysisResult.insights.personalityInferences.values?.length > 0 && (+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">Values</h4>+ <div className="flex flex-wrap gap-2">+ {analysisResult.insights.personalityInferences.values.map((value, i) => (+ <span+ key={i}+ className="px-2 py-1 bg-purple-500/20 text-purple-400 rounded-lg text-sm"+ >+ {value}+ </span>+ ))}+ </div>+ </div>+ )}+ {analysisResult.insights.personalityInferences.interests?.length > 0 && (+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">Interests</h4>+ <div className="flex flex-wrap gap-2">+ {analysisResult.insights.personalityInferences.interests.map((interest, i) => (+ <span+ key={i}+ className="px-2 py-1 bg-blue-500/20 text-blue-400 rounded-lg text-sm"+ >+ {interest}+ </span>+ ))}+ </div>+ </div>+ )}+ </div>+ </div>+ )}++ {/* Patterns & Preferences */}+ {(analysisResult.insights?.patterns?.length > 0 || analysisResult.insights?.preferences?.length > 0) && (+ <div className="bg-port-card rounded-lg border border-port-border p-6">+ <h3 className="text-lg font-semibold text-white mb-4">Patterns & Preferences</h3>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">+ {analysisResult.insights.patterns?.length > 0 && (+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">Patterns</h4>+ <ul className="space-y-2">+ {analysisResult.insights.patterns.map((pattern, i) => (+ <li key={i} className="text-sm text-gray-300 flex items-start gap-2">+ <ChevronRight className="w-4 h-4 text-port-accent flex-shrink-0 mt-0.5" />+ {pattern}+ </li>+ ))}+ </ul>+ </div>+ )}+ {analysisResult.insights.preferences?.length > 0 && (+ <div>+ <h4 className="text-sm font-medium text-gray-400 mb-2">Preferences</h4>+ <ul className="space-y-2">+ {analysisResult.insights.preferences.map((pref, i) => (+ <li key={i} className="text-sm text-gray-300 flex items-start gap-2">+ <ChevronRight className="w-4 h-4 text-green-400 flex-shrink-0 mt-0.5" />+ {pref}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </div>+ )}++ {/* Suggested Documents */}+ {analysisResult.suggestedDocuments?.length > 0 && (+ <div className="bg-port-card rounded-lg border border-port-border p-6">+ <h3 className="text-lg font-semibold text-white mb-4">Save as Documents</h3>+ <p className="text-sm text-gray-400 mb-4">+ These documents have been generated from your {selectedSource?.name} data.+ Save them to add this information to your digital twin.+ </p>+ <div className="space-y-3">+ {analysisResult.suggestedDocuments.map((doc, i) => (+ <div+ key={i}+ className="p-4 bg-port-bg rounded-lg border border-port-border"+ >+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <FileText className="w-4 h-4 text-gray-400" />+ <span className="font-medium text-white">{doc.title}</span>+ <span className="text-xs text-gray-500 bg-port-card px-2 py-0.5 rounded">+ {doc.category}+ </span>+ </div>+ <button+ onClick={() => handleSaveDocument(doc)}+ disabled={saving}+ className="px-3 py-1.5 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 disabled:opacity-50 flex items-center gap-1"+ >+ <Save className="w-4 h-4" />+ Save+ </button>+ </div>+ <p className="text-xs text-gray-500">{doc.filename}</p>+ <details className="mt-2">+ <summary className="text-sm text-port-accent cursor-pointer hover:text-white">+ Preview content+ </summary>+ <pre className="mt-2 p-3 bg-port-card rounded text-xs text-gray-300 overflow-x-auto whitespace-pre-wrap max-h-48 overflow-y-auto">+ {doc.content}+ </pre>+ </details>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsxindex 7dc27f79ea..5796dd88d7 100644--- a/client/src/pages/DigitalTwin.jsx+++ b/client/src/pages/DigitalTwin.jsx@@ -9,6 +9,7 @@ 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 ImportTab from '../components/digital-twin/tabs/ImportTab';import ExportTab from '../components/digital-twin/tabs/ExportTab';export default function DigitalTwin() {@@ -50,6 +51,8 @@ export default function DigitalTwin() {return <TestTab onRefresh={fetchData} />;case 'enrich':return <EnrichTab onRefresh={fetchData} />;+ case 'import':+ return <ImportTab onRefresh={fetchData} />;case 'export':return <ExportTab onRefresh={fetchData} />;default:diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 0bc29b3772..e0455c994a 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -665,6 +665,17 @@ export const calculateDigitalTwinConfidence = (providerId, model) => request('/d});export const getDigitalTwinGaps = () => request('/digital-twin/gaps');+// --- Digital Twin External Import (Phase 4) ---+export const getDigitalTwinImportSources = () => request('/digital-twin/import/sources');+export const analyzeDigitalTwinImport = (source, data, providerId, model) => request('/digital-twin/import/analyze', {+ method: 'POST',+ body: JSON.stringify({ source, data, providerId, model })+});+export const saveDigitalTwinImport = (source, suggestedDoc) => request('/digital-twin/import/save', {+ method: 'POST',+ body: JSON.stringify({ source, suggestedDoc })+});+// Default export for simplified importsexport default {get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex f6047864c5..6be5cf968f 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -299,3 +299,82 @@ export const calculateConfidenceInputSchema = z.object({providerId: z.string().min(1).optional(),model: z.string().min(1).optional()});++// --- Phase 4: External Data Import Schemas ---++// Import source enum+export const importSourceEnum = z.enum([+ 'goodreads',+ 'spotify',+ 'lastfm',+ 'letterboxd',+ 'ical'+]);++// Goodreads book entry (parsed from CSV)+export const goodreadsBookSchema = z.object({+ title: z.string(),+ author: z.string().optional(),+ rating: z.number().min(0).max(5).optional(),+ dateRead: z.string().optional(),+ shelves: z.array(z.string()).optional(),+ review: z.string().optional()+});++// Spotify track/artist entry (parsed from JSON export)+export const spotifyEntrySchema = z.object({+ trackName: z.string().optional(),+ artistName: z.string(),+ albumName: z.string().optional(),+ playCount: z.number().int().optional(),+ msPlayed: z.number().int().optional()+});++// Letterboxd film entry+export const letterboxdFilmSchema = z.object({+ title: z.string(),+ year: z.number().int().optional(),+ rating: z.number().min(0).max(5).optional(),+ watchedDate: z.string().optional(),+ review: z.string().optional(),+ tags: z.array(z.string()).optional()+});++// Calendar event for pattern analysis+export const calendarEventSchema = z.object({+ summary: z.string(),+ start: z.string(),+ end: z.string().optional(),+ recurring: z.boolean().optional(),+ categories: z.array(z.string()).optional()+});++// Import data input (raw data to parse)+export const importDataInputSchema = z.object({+ source: importSourceEnum,+ data: z.string().min(1).max(10000000), // Up to 10MB of text data+ providerId: z.string().min(1),+ model: z.string().min(1)+});++// Import analysis result+export const importAnalysisResultSchema = z.object({+ source: importSourceEnum,+ itemCount: z.number().int(),+ insights: z.object({+ patterns: z.array(z.string()).optional(),+ preferences: z.array(z.string()).optional(),+ personalityInferences: z.object({+ bigFive: bigFiveSchema.partial().optional(),+ values: z.array(z.string()).optional(),+ interests: z.array(z.string()).optional()+ }).optional()+ }),+ suggestedDocuments: z.array(z.object({+ filename: z.string(),+ title: z.string(),+ category: documentCategoryEnum,+ content: z.string()+ })).optional(),+ rawSummary: z.string().optional()+});diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.jsindex 0e104e2017..6ddac66b9c 100644--- a/server/routes/digital-twin.js+++ b/server/routes/digital-twin.js@@ -31,7 +31,8 @@ import {getListItemsInputSchema,analyzeTraitsInputSchema,updateTraitsInputSchema,- calculateConfidenceInputSchema+ calculateConfidenceInputSchema,+ importDataInputSchema} from '../lib/digitalTwinValidation.js';const router = Router();@@ -548,4 +549,62 @@ router.get('/gaps', asyncHandler(async (req, res) => {res.json({ gaps });}));+// =============================================================================+// EXTERNAL DATA IMPORT (Phase 4)+// =============================================================================++/**+ * GET /api/digital-twin/import/sources+ * Get list of supported import sources+ */+router.get('/import/sources', asyncHandler(async (req, res) => {+ const sources = digitalTwinService.getImportSources();+ res.json({ sources });+}));++/**+ * POST /api/digital-twin/import/analyze+ * Analyze imported external data+ */+router.post('/import/analyze', asyncHandler(async (req, res) => {+ const validation = validate(importDataInputSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', {+ status: 400,+ code: 'VALIDATION_ERROR',+ context: { details: validation.errors }+ });+ }++ const { source, data, providerId, model } = validation.data;+ const result = await digitalTwinService.analyzeImportedData(source, data, providerId, model);++ if (result.error) {+ throw new ServerError(result.error, {+ status: 400,+ code: 'IMPORT_ANALYSIS_ERROR'+ });+ }++ res.json(result);+}));++/**+ * POST /api/digital-twin/import/save+ * Save import analysis as a document+ */+router.post('/import/save', asyncHandler(async (req, res) => {+ const { source, suggestedDoc } = req.body;++ if (!source || !suggestedDoc || !suggestedDoc.filename || !suggestedDoc.content) {+ throw new ServerError('Missing required fields: source and suggestedDoc', {+ status: 400,+ code: 'VALIDATION_ERROR'+ });+ }++ const document = await digitalTwinService.saveImportAsDocument(source, suggestedDoc);+ res.json({ document, message: 'Document saved successfully' });+}));+export default router;diff --git a/server/services/digital-twin.js b/server/services/digital-twin.jsindex af610cfd4b..583371dc73 100644--- a/server/services/digital-twin.js+++ b/server/services/digital-twin.js@@ -2127,3 +2127,493 @@ export async function getGapRecommendations() {return meta.confidence.gaps || [];}++// =============================================================================+// EXTERNAL DATA IMPORT (Phase 4)+// =============================================================================++/**+ * Parse Goodreads CSV export+ * CSV columns: Book Id, Title, Author, Author l-f, Additional Authors, ISBN, ISBN13,+ * My Rating, Average Rating, Publisher, Binding, Number of Pages, Year Published,+ * Original Publication Year, Date Read, Date Added, Bookshelves, Bookshelves with positions,+ * Exclusive Shelf, My Review, Spoiler, Private Notes, Read Count, Owned Copies+ */+function parseGoodreadsCSV(csvData) {+ const lines = csvData.split('\n');+ if (lines.length < 2) return [];++ // Parse header to find column indices+ const header = parseCSVLine(lines[0]);+ const titleIdx = header.findIndex(h => h.toLowerCase() === 'title');+ const authorIdx = header.findIndex(h => h.toLowerCase() === 'author');+ const ratingIdx = header.findIndex(h => h.toLowerCase() === 'my rating');+ const dateReadIdx = header.findIndex(h => h.toLowerCase() === 'date read');+ const shelvesIdx = header.findIndex(h => h.toLowerCase() === 'bookshelves');+ const reviewIdx = header.findIndex(h => h.toLowerCase() === 'my review');++ const books = [];+ for (let i = 1; i < lines.length; i++) {+ if (!lines[i].trim()) continue;+ const cols = parseCSVLine(lines[i]);++ const rating = ratingIdx >= 0 ? parseInt(cols[ratingIdx]) : 0;+ // Only include books that were actually read (have a rating > 0 or date read)+ if (rating > 0 || (dateReadIdx >= 0 && cols[dateReadIdx])) {+ books.push({+ title: cols[titleIdx] || '',+ author: cols[authorIdx] || '',+ rating: rating || undefined,+ dateRead: dateReadIdx >= 0 ? cols[dateReadIdx] : undefined,+ shelves: shelvesIdx >= 0 && cols[shelvesIdx] ? cols[shelvesIdx].split(',').map(s => s.trim()) : [],+ review: reviewIdx >= 0 ? cols[reviewIdx] : undefined+ });+ }+ }++ return books;+}++/**+ * Parse a CSV line handling quoted fields+ */+function parseCSVLine(line) {+ const result = [];+ let current = '';+ let inQuotes = false;++ for (let i = 0; i < line.length; i++) {+ const char = line[i];+ if (char === '"') {+ if (inQuotes && line[i + 1] === '"') {+ current += '"';+ i++;+ } else {+ inQuotes = !inQuotes;+ }+ } else if (char === ',' && !inQuotes) {+ result.push(current.trim());+ current = '';+ } else {+ current += char;+ }+ }+ result.push(current.trim());++ return result;+}++/**+ * Parse Spotify extended streaming history JSON+ * Spotify exports: endTime, artistName, trackName, msPlayed+ */+function parseSpotifyJSON(jsonData) {+ const data = JSON.parse(jsonData);++ // Handle both array format and object with streams array+ const streams = Array.isArray(data) ? data : (data.streams || data);+ if (!Array.isArray(streams)) return [];++ // Aggregate by artist+ const artistCounts = new Map();+ const trackCounts = new Map();++ for (const entry of streams) {+ const artist = entry.artistName || entry.master_metadata_album_artist_name;+ const track = entry.trackName || entry.master_metadata_track_name;+ const msPlayed = entry.msPlayed || entry.ms_played || 0;++ if (artist) {+ const existing = artistCounts.get(artist) || { playCount: 0, msPlayed: 0 };+ artistCounts.set(artist, {+ playCount: existing.playCount + 1,+ msPlayed: existing.msPlayed + msPlayed+ });+ }++ if (track && artist) {+ const key = `${track}|||${artist}`;+ const existing = trackCounts.get(key) || { playCount: 0, msPlayed: 0 };+ trackCounts.set(key, {+ trackName: track,+ artistName: artist,+ playCount: existing.playCount + 1,+ msPlayed: existing.msPlayed + msPlayed+ });+ }+ }++ // Return top artists and tracks+ const topArtists = Array.from(artistCounts.entries())+ .map(([name, data]) => ({ artistName: name, ...data }))+ .sort((a, b) => b.msPlayed - a.msPlayed)+ .slice(0, 50);++ const topTracks = Array.from(trackCounts.values())+ .sort((a, b) => b.playCount - a.playCount)+ .slice(0, 50);++ return { artists: topArtists, tracks: topTracks };+}++/**+ * Parse Letterboxd CSV export+ */+function parseLetterboxdCSV(csvData) {+ const lines = csvData.split('\n');+ if (lines.length < 2) return [];++ const header = parseCSVLine(lines[0]);+ const nameIdx = header.findIndex(h => h.toLowerCase().includes('name') || h.toLowerCase() === 'title');+ const yearIdx = header.findIndex(h => h.toLowerCase() === 'year');+ const ratingIdx = header.findIndex(h => h.toLowerCase() === 'rating');+ const dateIdx = header.findIndex(h => h.toLowerCase().includes('watched'));+ const reviewIdx = header.findIndex(h => h.toLowerCase() === 'review');+ const tagsIdx = header.findIndex(h => h.toLowerCase() === 'tags');++ const films = [];+ for (let i = 1; i < lines.length; i++) {+ if (!lines[i].trim()) continue;+ const cols = parseCSVLine(lines[i]);++ films.push({+ title: cols[nameIdx] || cols[0] || '',+ year: yearIdx >= 0 && cols[yearIdx] ? parseInt(cols[yearIdx]) : undefined,+ rating: ratingIdx >= 0 && cols[ratingIdx] ? parseFloat(cols[ratingIdx]) : undefined,+ watchedDate: dateIdx >= 0 ? cols[dateIdx] : undefined,+ review: reviewIdx >= 0 ? cols[reviewIdx] : undefined,+ tags: tagsIdx >= 0 && cols[tagsIdx] ? cols[tagsIdx].split(',').map(t => t.trim()) : []+ });+ }++ return films.filter(f => f.title);+}++/**+ * Parse iCal/ICS calendar file+ */+function parseICalData(icsData) {+ const events = [];+ const eventBlocks = icsData.split('BEGIN:VEVENT');++ for (let i = 1; i < eventBlocks.length; i++) {+ const block = eventBlocks[i].split('END:VEVENT')[0];+ const event = {};++ const summaryMatch = block.match(/SUMMARY[^:]*:(.+?)(?:\r?\n(?![^\r\n])|\r?\n[A-Z])/s);+ if (summaryMatch) event.summary = summaryMatch[1].replace(/\r?\n\s/g, '').trim();++ const startMatch = block.match(/DTSTART[^:]*:(\d{8}T?\d{0,6})/);+ if (startMatch) event.start = startMatch[1];++ const endMatch = block.match(/DTEND[^:]*:(\d{8}T?\d{0,6})/);+ if (endMatch) event.end = endMatch[1];++ const rruleMatch = block.match(/RRULE:/);+ event.recurring = !!rruleMatch;++ const categoriesMatch = block.match(/CATEGORIES[^:]*:(.+?)(?:\r?\n[A-Z])/s);+ if (categoriesMatch) {+ event.categories = categoriesMatch[1].split(',').map(c => c.trim());+ }++ if (event.summary) {+ events.push(event);+ }+ }++ return events;+}++/**+ * Analyze imported data and extract personality insights+ */+export async function analyzeImportedData(source, rawData, providerId, model) {+ let parsedData;+ let dataDescription;++ // Parse based on source+ switch (source) {+ case 'goodreads': {+ parsedData = parseGoodreadsCSV(rawData);+ if (parsedData.length === 0) {+ return { error: 'No books found in Goodreads export. Make sure you exported your library.' };+ }+ const topRated = parsedData.filter(b => b.rating >= 4).slice(0, 20);+ const authors = [...new Set(parsedData.map(b => b.author).filter(Boolean))].slice(0, 20);+ const shelves = [...new Set(parsedData.flatMap(b => b.shelves || []))].slice(0, 15);+ dataDescription = `Reading History (${parsedData.length} books):\n` ++ `Top-rated books: ${topRated.map(b => `"${b.title}" by ${b.author} (${b.rating}/5)`).join(', ')}\n` ++ `Favorite authors: ${authors.join(', ')}\n` ++ `Shelves/genres: ${shelves.join(', ')}\n` ++ `Sample reviews: ${parsedData.filter(b => b.review).slice(0, 3).map(b => `"${b.title}": ${b.review?.substring(0, 200)}...`).join('\n')}`;+ break;+ }++ case 'spotify': {+ parsedData = parseSpotifyJSON(rawData);+ if (!parsedData.artists || parsedData.artists.length === 0) {+ return { error: 'No listening data found in Spotify export.' };+ }+ const topArtists = parsedData.artists.slice(0, 15);+ const topTracks = parsedData.tracks?.slice(0, 15) || [];+ const totalHours = Math.round(topArtists.reduce((sum, a) => sum + a.msPlayed, 0) / 3600000);+ dataDescription = `Listening History (${totalHours} hours tracked):\n` ++ `Top artists: ${topArtists.map(a => `${a.artistName} (${Math.round(a.msPlayed / 60000)} min)`).join(', ')}\n` ++ `Top tracks: ${topTracks.map(t => `"${t.trackName}" by ${t.artistName}`).join(', ')}`;+ break;+ }++ case 'letterboxd': {+ parsedData = parseLetterboxdCSV(rawData);+ if (parsedData.length === 0) {+ return { error: 'No films found in Letterboxd export.' };+ }+ const topRated = parsedData.filter(f => f.rating >= 4).slice(0, 20);+ const tags = [...new Set(parsedData.flatMap(f => f.tags || []))].slice(0, 15);+ dataDescription = `Film History (${parsedData.length} films):\n` ++ `Top-rated films: ${topRated.map(f => `"${f.title}" (${f.year}) - ${f.rating}/5`).join(', ')}\n` ++ `Tags/themes: ${tags.join(', ')}\n` ++ `Sample reviews: ${parsedData.filter(f => f.review).slice(0, 3).map(f => `"${f.title}": ${f.review?.substring(0, 200)}...`).join('\n')}`;+ break;+ }++ case 'ical': {+ parsedData = parseICalData(rawData);+ if (parsedData.length === 0) {+ return { error: 'No events found in calendar export.' };+ }+ const recurring = parsedData.filter(e => e.recurring);+ const categories = [...new Set(parsedData.flatMap(e => e.categories || []))];+ const eventTypes = {};+ parsedData.forEach(e => {+ const type = categorizeEvent(e.summary);+ eventTypes[type] = (eventTypes[type] || 0) + 1;+ });+ dataDescription = `Calendar Analysis (${parsedData.length} events, ${recurring.length} recurring):\n` ++ `Event types: ${Object.entries(eventTypes).map(([k, v]) => `${k}: ${v}`).join(', ')}\n` ++ `Categories: ${categories.join(', ')}\n` ++ `Recurring commitments: ${recurring.slice(0, 10).map(e => e.summary).join(', ')}`;+ break;+ }++ default:+ return { error: `Unknown import source: ${source}` };+ }++ // Build analysis prompt+ const prompt = await buildPrompt('twin-import-analyzer', {+ source,+ dataDescription,+ itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0)+ }).catch(() => null);++ if (!prompt) {+ // Fallback to inline prompt+ const fallbackPrompt = buildImportAnalyzerPrompt(source, dataDescription);+ return analyzeWithPrompt(fallbackPrompt, providerId, model, source, parsedData);+ }++ return analyzeWithPrompt(prompt, providerId, model, source, parsedData);+}++/**+ * Categorize calendar event by its summary+ */+function categorizeEvent(summary) {+ const lower = (summary || '').toLowerCase();+ if (lower.includes('meeting') || lower.includes('call') || lower.includes('sync')) return 'work';+ if (lower.includes('gym') || lower.includes('workout') || lower.includes('run') || lower.includes('yoga')) return 'fitness';+ if (lower.includes('doctor') || lower.includes('dentist') || lower.includes('appointment')) return 'health';+ if (lower.includes('dinner') || lower.includes('lunch') || lower.includes('coffee')) return 'social';+ if (lower.includes('class') || lower.includes('lesson') || lower.includes('course')) return 'learning';+ if (lower.includes('travel') || lower.includes('flight') || lower.includes('trip')) return 'travel';+ return 'other';+}++/**+ * Build fallback prompt for import analysis+ */+function buildImportAnalyzerPrompt(source, dataDescription) {+ const sourceLabels = {+ goodreads: 'reading history',+ spotify: 'music listening history',+ letterboxd: 'film watching history',+ ical: 'calendar/schedule patterns'+ };++ return `Analyze this ${sourceLabels[source] || source} data to understand the person's personality, values, and interests.++## Data+${dataDescription}++## Analysis Instructions+Based on this data, infer:++1. **Personality Traits (Big Five)**: What does their ${sourceLabels[source]} suggest about their Openness, Conscientiousness, Extraversion, Agreeableness, and Neuroticism? Provide estimates from 0.0 to 1.0.++2. **Values**: What values seem important to this person based on their choices?++3. **Interests & Themes**: What topics, genres, or themes do they gravitate toward?++4. **Patterns**: Any notable patterns in their behavior (e.g., variety vs. consistency, niche vs. mainstream)?++5. **Suggested Document Content**: Write a short markdown document summarizing key insights about their ${sourceLabels[source]} preferences.++## Output Format+Respond with JSON only:++\`\`\`json+{+ "insights": {+ "patterns": ["pattern 1", "pattern 2"],+ "preferences": ["preference 1", "preference 2"],+ "personalityInferences": {+ "bigFive": { "O": 0.7, "C": 0.6, "E": 0.5, "A": 0.6, "N": 0.4 },+ "values": ["value1", "value2"],+ "interests": ["interest1", "interest2"]+ }+ },+ "suggestedDocuments": [+ {+ "filename": "READING_PROFILE.md",+ "title": "Reading Profile",+ "category": "entertainment",+ "content": "# Reading Profile\\n\\nMarkdown content here..."+ }+ ],+ "rawSummary": "2-3 sentence summary of what this data reveals about the person"+}+\`\`\``;+}++/**+ * Send prompt to AI and parse response+ */+async function analyzeWithPrompt(prompt, providerId, model, source, parsedData) {+ 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.4,+ max_tokens: 3000+ })+ });++ if (response.ok) {+ const data = await response.json();+ const responseText = data.choices?.[0]?.message?.content || '';+ return parseImportAnalysisResponse(responseText, source, parsedData);+ }++ return { error: `Provider request failed: ${response.status}` };+ }++ return { error: 'Provider type not supported' };+}++/**+ * Parse AI response for import analysis+ */+function parseImportAnalysisResponse(response, source, parsedData) {+ const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);+ if (jsonMatch) {+ const parsed = JSON.parse(jsonMatch[1]);+ return {+ source,+ itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),+ ...parsed+ };+ }++ if (response.trim().startsWith('{')) {+ const parsed = JSON.parse(response);+ return {+ source,+ itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),+ ...parsed+ };+ }++ return {+ source,+ itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),+ insights: { patterns: [], preferences: [] },+ rawSummary: response+ };+}++/**+ * Save imported analysis as a document+ */+export async function saveImportAsDocument(source, suggestedDoc) {+ const { filename, title, category, content } = suggestedDoc;++ // Check if document already exists+ const meta = await loadMeta();+ const existingDoc = meta.documents.find(d => d.filename === filename);++ if (existingDoc) {+ // Update existing document+ return updateDocument(existingDoc.id, { content, title });+ }++ // Create new document+ return createDocument({+ filename,+ title,+ category,+ content,+ enabled: true,+ priority: 5+ });+}++/**+ * Get list of supported import sources+ */+export function getImportSources() {+ return [+ {+ id: 'goodreads',+ name: 'Goodreads',+ description: 'Import your reading history to analyze literary preferences and themes',+ format: 'CSV',+ instructions: 'Go to My Books > Import/Export > Export Library. Download the CSV file.'+ },+ {+ id: 'spotify',+ name: 'Spotify',+ description: 'Import listening history to analyze music preferences and emotional patterns',+ format: 'JSON',+ instructions: 'Go to Account > Privacy Settings > Download your data. Request "Extended streaming history". Extract the JSON files.'+ },+ {+ id: 'letterboxd',+ name: 'Letterboxd',+ description: 'Import film diary to analyze viewing preferences and aesthetic tastes',+ format: 'CSV',+ instructions: 'Go to Settings > Import & Export > Export Your Data. Download the diary.csv or films.csv.'+ },+ {+ id: 'ical',+ name: 'Calendar (iCal)',+ description: 'Import calendar to analyze routine patterns and time allocation',+ format: 'ICS',+ instructions: 'Export your calendar as .ics file from Google Calendar, Apple Calendar, or Outlook.'+ }+ ];+}