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 Time Capsule Snapshots for identity preservation
Adam Eivy9006bf2f95ac
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..60df9d739a--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,3 @@+## Added++- Time Capsule Snapshots for Digital Twin — create versioned archives of your complete digital twin (documents, traits, goals, genome, autobiography, test history) to track identity evolution over time. Includes create, view, compare, and delete functionality with a dedicated tab at `/digital-twin/time-capsule`diff --git a/PLAN.md b/PLAN.mdindex 8460c7f56c..3d87d92223 100644--- a/PLAN.md+++ b/PLAN.md@@ -28,7 +28,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]- **Proactive Insight Alerts** — Brain connections, success drops, goal stalls, cost spikes- **Goal Decomposition Engine** — Auto-decompose goals into task sequences- **Knowledge Graph Visualization** — Extend BrainGraph 3D to full knowledge graph-- **Time Capsule Snapshots** — Periodic versioned digital twin archives+- [x] **Time Capsule Snapshots** — Periodic versioned digital twin archives- **Autobiography Prompt Chains** — LLM follow-ups building on prior answers- **Legacy Export Format** — Identity as portable Markdown/PDF- **Dashboard Customization** — Drag-and-drop widgets, named layoutsdiff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.jsindex e8aad787ba..e1bcf68ce8 100644--- a/client/src/components/digital-twin/constants.js+++ b/client/src/components/digital-twin/constants.js@@ -24,7 +24,8 @@ import {Fingerprint,Globe,PenLine,- Target+ Target,+ Archive} from 'lucide-react';// Main navigation tabs@@ -40,7 +41,8 @@ export const TABS = [{ id: 'interview', label: 'Interview', icon: MessageSquare },{ id: 'autobiography', label: 'Autobiography', icon: PenLine },{ id: 'import', label: 'Import', icon: Upload },- { id: 'export', label: 'Export', icon: Download }+ { id: 'export', label: 'Export', icon: Download },+ { id: 'time-capsule', label: 'Time Capsule', icon: Archive }];// Document category configurationsdiff --git a/client/src/components/digital-twin/tabs/TimeCapsuleTab.jsx b/client/src/components/digital-twin/tabs/TimeCapsuleTab.jsxnew file mode 100644index 0000000000..a8fc70bcbc--- /dev/null+++ b/client/src/components/digital-twin/tabs/TimeCapsuleTab.jsx@@ -0,0 +1,483 @@+import { useState, useEffect, useCallback } from 'react';+import {+ Archive,+ Plus,+ Trash2,+ Eye,+ GitCompare,+ RefreshCw,+ Calendar,+ FileText,+ Target,+ BookOpen,+ Dna,+ CheckCircle,+ ChevronDown,+ ChevronUp,+ X+} from 'lucide-react';+import * as api from '../../../services/api';+import toast from 'react-hot-toast';++function formatBytes(bytes) {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}++function formatDate(iso) {+ return new Date(iso).toLocaleDateString('en-US', {+ year: 'numeric', month: 'short', day: 'numeric',+ hour: '2-digit', minute: '2-digit'+ });+}++function timeAgo(iso) {+ const diff = Date.now() - new Date(iso).getTime();+ const days = Math.floor(diff / 86400000);+ if (days === 0) return 'today';+ if (days === 1) return 'yesterday';+ if (days < 30) return `${days}d ago`;+ if (days < 365) return `${Math.floor(days / 30)}mo ago`;+ return `${Math.floor(days / 365)}y ago`;+}++export default function TimeCapsuleTab({ onRefresh: _onRefresh }) {+ const [snapshots, setSnapshots] = useState([]);+ const [loading, setLoading] = useState(true);+ const [creating, setCreating] = useState(false);++ // Create form+ const [showForm, setShowForm] = useState(false);+ const [label, setLabel] = useState('');+ const [description, setDescription] = useState('');++ // Detail view+ const [viewingSnapshot, setViewingSnapshot] = useState(null);+ const [viewLoading, setViewLoading] = useState(false);++ // Compare+ const [compareMode, setCompareMode] = useState(false);+ const [compareIds, setCompareIds] = useState([]);+ const [compareResult, setCompareResult] = useState(null);+ const [comparing, setComparing] = useState(false);++ // Delete confirmation+ const [confirmDelete, setConfirmDelete] = useState(null);++ const loadSnapshots = useCallback(async () => {+ setLoading(true);+ const data = await api.listTimeCapsuleSnapshots().catch(() => []);+ setSnapshots(data);+ setLoading(false);+ }, []);++ useEffect(() => { loadSnapshots(); }, [loadSnapshots]);++ const handleCreate = async () => {+ if (!label.trim()) return;+ setCreating(true);+ const snapshot = await api.createTimeCapsuleSnapshot(label.trim(), description.trim());+ setSnapshots(prev => [snapshot, ...prev]);+ setLabel('');+ setDescription('');+ setShowForm(false);+ setCreating(false);+ toast.success(`Snapshot "${snapshot.label}" created`);+ };++ const handleDelete = async (id) => {+ const snap = snapshots.find(s => s.id === id);+ await api.deleteTimeCapsuleSnapshot(id);+ setSnapshots(prev => prev.filter(s => s.id !== id));+ setConfirmDelete(null);+ if (viewingSnapshot?.id === id) setViewingSnapshot(null);+ toast.success(`Snapshot "${snap?.label}" deleted`);+ };++ const handleView = async (id) => {+ if (viewingSnapshot?.id === id) {+ setViewingSnapshot(null);+ return;+ }+ setViewLoading(true);+ const data = await api.getTimeCapsuleSnapshot(id);+ setViewingSnapshot(data);+ setViewLoading(false);+ };++ const toggleCompareId = (id) => {+ setCompareIds(prev => {+ if (prev.includes(id)) return prev.filter(i => i !== id);+ if (prev.length >= 2) return [prev[1], id];+ return [...prev, id];+ });+ setCompareResult(null);+ };++ const handleCompare = async () => {+ if (compareIds.length !== 2) return;+ setComparing(true);+ const result = await api.compareTimeCapsuleSnapshots(compareIds[0], compareIds[1]);+ setCompareResult(result);+ setComparing(false);+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />+ </div>+ );+ }++ return (+ <div className="space-y-4">+ {/* Header */}+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">+ <div>+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">+ <Archive size={20} />+ Time Capsule+ </h2>+ <p className="text-sm text-gray-500">+ {snapshots.length} snapshot{snapshots.length !== 1 ? 's' : ''} archived+ </p>+ </div>+ <div className="flex gap-2">+ {snapshots.length >= 2 && (+ <button+ onClick={() => {+ setCompareMode(!compareMode);+ setCompareIds([]);+ setCompareResult(null);+ }}+ className={`flex items-center gap-2 px-3 py-2 min-h-[40px] rounded-lg border text-sm transition-colors ${+ compareMode+ ? 'border-port-accent text-port-accent bg-port-accent/10'+ : 'border-port-border text-gray-400 hover:text-white hover:border-gray-500'+ }`}+ >+ <GitCompare size={16} />+ Compare+ </button>+ )}+ <button+ onClick={() => setShowForm(!showForm)}+ className="flex items-center gap-2 px-4 py-2 min-h-[40px] bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80"+ >+ <Plus size={16} />+ New Snapshot+ </button>+ </div>+ </div>++ {/* Create Form */}+ {showForm && (+ <div className="bg-port-card rounded-lg border border-port-accent/30 p-4">+ <h3 className="font-medium text-white mb-3">Create Snapshot</h3>+ <div className="space-y-3">+ <input+ type="text"+ value={label}+ onChange={e => setLabel(e.target.value)}+ placeholder="Snapshot label (e.g., Spring 2026, Pre-career-change)"+ className="w-full px-3 py-2 min-h-[40px] bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"+ autoFocus+ onKeyDown={e => e.key === 'Enter' && label.trim() && handleCreate()}+ />+ <textarea+ value={description}+ onChange={e => setDescription(e.target.value)}+ placeholder="Optional notes about this moment in time..."+ rows={2}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent resize-none"+ />+ <div className="flex justify-end gap-2">+ <button+ onClick={() => { setShowForm(false); setLabel(''); setDescription(''); }}+ className="px-4 py-2 min-h-[40px] text-gray-400 hover:text-white text-sm"+ >+ Cancel+ </button>+ <button+ onClick={handleCreate}+ disabled={!label.trim() || creating}+ className="flex items-center gap-2 px-4 py-2 min-h-[40px] bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {creating ? <RefreshCw size={14} className="animate-spin" /> : <Archive size={14} />}+ {creating ? 'Creating...' : 'Create Snapshot'}+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Compare Mode Banner */}+ {compareMode && (+ <div className="bg-port-card rounded-lg border border-port-accent/30 p-3 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">+ <p className="text-sm text-gray-400">+ Select 2 snapshots to compare ({compareIds.length}/2 selected)+ </p>+ <div className="flex gap-2">+ <button+ onClick={() => { setCompareMode(false); setCompareIds([]); setCompareResult(null); }}+ className="px-3 py-1.5 min-h-[36px] text-sm text-gray-400 hover:text-white"+ >+ Cancel+ </button>+ <button+ onClick={handleCompare}+ disabled={compareIds.length !== 2 || comparing}+ className="flex items-center gap-2 px-4 py-1.5 min-h-[36px] bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {comparing ? <RefreshCw size={14} className="animate-spin" /> : <GitCompare size={14} />}+ Compare+ </button>+ </div>+ </div>+ )}++ {/* Compare Result */}+ {compareResult && (+ <div className="bg-port-card rounded-lg border border-port-border p-4">+ <div className="flex items-center justify-between mb-3">+ <h3 className="font-medium text-white flex items-center gap-2">+ <GitCompare size={16} />+ Comparison: {compareResult.snapshot1.label} vs {compareResult.snapshot2.label}+ </h3>+ <button onClick={() => setCompareResult(null)} className="p-1 text-gray-400 hover:text-white">+ <X size={16} />+ </button>+ </div>+ <div className="text-xs text-gray-500 mb-3">+ {formatDate(compareResult.snapshot1.createdAt)} → {formatDate(compareResult.snapshot2.createdAt)}+ </div>+ {compareResult.changes.length === 0 ? (+ <p className="text-sm text-gray-500">No differences found between these snapshots.</p>+ ) : (+ <div className="space-y-2">+ {compareResult.changes.map((change, i) => (+ <div key={i} className="flex items-start gap-3 p-2 bg-port-bg rounded-lg text-sm">+ <span className="text-gray-400 font-medium min-w-[140px] shrink-0">{change.field}</span>+ {change.before !== undefined && change.after !== undefined ? (+ <span className="text-gray-300">+ <span className="text-red-400">{JSON.stringify(change.before)}</span>+ {' → '}+ <span className="text-green-400">{JSON.stringify(change.after)}</span>+ </span>+ ) : (+ <span className="text-gray-300">+ {Array.isArray(change.value) ? change.value.join(', ') : JSON.stringify(change.value)}+ </span>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ )}++ {/* Empty State */}+ {snapshots.length === 0 && !showForm && (+ <div className="bg-port-card rounded-lg border border-port-border p-8 text-center">+ <Archive className="w-12 h-12 mx-auto mb-4 text-gray-600" />+ <h3 className="text-white font-medium mb-2">No snapshots yet</h3>+ <p className="text-sm text-gray-500 mb-4 max-w-md mx-auto">+ Create your first time capsule to preserve a snapshot of your digital twin.+ Track how your identity evolves over time.+ </p>+ <button+ onClick={() => setShowForm(true)}+ className="inline-flex items-center gap-2 px-4 py-2 min-h-[40px] bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80"+ >+ <Plus size={16} />+ Create First Snapshot+ </button>+ </div>+ )}++ {/* Snapshot List */}+ {snapshots.length > 0 && (+ <div className="space-y-2">+ {snapshots.map(snap => {+ const isViewing = viewingSnapshot?.id === snap.id;+ const isCompareSelected = compareIds.includes(snap.id);++ return (+ <div key={snap.id}>+ <div className={`bg-port-card rounded-lg border transition-colors ${+ isCompareSelected ? 'border-port-accent' : 'border-port-border'+ }`}>+ <div className="flex items-center gap-3 p-3 sm:p-4">+ {/* Compare checkbox */}+ {compareMode && (+ <input+ type="checkbox"+ checked={isCompareSelected}+ onChange={() => toggleCompareId(snap.id)}+ className="w-5 h-5 shrink-0 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ )}++ {/* Info */}+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-1">+ <span className="font-medium text-white truncate">{snap.label}</span>+ <span className="text-xs text-gray-500 shrink-0">{timeAgo(snap.createdAt)}</span>+ </div>+ {snap.description && (+ <p className="text-sm text-gray-500 truncate mb-1">{snap.description}</p>+ )}+ <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-gray-500">+ <span className="flex items-center gap-1">+ <FileText size={12} />+ {snap.summary?.documentCount ?? 0} docs+ </span>+ <span className="flex items-center gap-1">+ <Target size={12} />+ {snap.summary?.goalsCount ?? 0} goals+ </span>+ <span className="flex items-center gap-1">+ <BookOpen size={12} />+ {snap.summary?.storiesCount ?? 0} stories+ </span>+ {(snap.summary?.genomeMarkers ?? 0) > 0 && (+ <span className="flex items-center gap-1">+ <Dna size={12} />+ {snap.summary.genomeMarkers} markers+ </span>+ )}+ <span className="flex items-center gap-1">+ <CheckCircle size={12} />+ {snap.summary?.testHistoryCount ?? 0} tests+ </span>+ <span className="text-gray-600">{formatBytes(snap.sizeBytes)}</span>+ </div>+ </div>++ {/* Actions */}+ {!compareMode && (+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={() => handleView(snap.id)}+ className={`p-2 min-h-[40px] min-w-[40px] flex items-center justify-center rounded-lg transition-colors ${+ isViewing ? 'text-port-accent bg-port-accent/10' : 'text-gray-400 hover:text-white hover:bg-port-border'+ }`}+ title={isViewing ? 'Close details' : 'View details'}+ >+ {viewLoading && viewingSnapshot === null ? (+ <RefreshCw size={16} className="animate-spin" />+ ) : isViewing ? (+ <ChevronUp size={16} />+ ) : (+ <ChevronDown size={16} />+ )}+ </button>+ {confirmDelete === snap.id ? (+ <div className="flex items-center gap-1">+ <button+ onClick={() => handleDelete(snap.id)}+ className="px-2 py-1 min-h-[40px] text-xs text-red-400 hover:text-red-300 font-medium"+ >+ Confirm+ </button>+ <button+ onClick={() => setConfirmDelete(null)}+ className="px-2 py-1 min-h-[40px] text-xs text-gray-500 hover:text-white"+ >+ Cancel+ </button>+ </div>+ ) : (+ <button+ onClick={() => setConfirmDelete(snap.id)}+ className="p-2 min-h-[40px] min-w-[40px] flex items-center justify-center text-gray-400 hover:text-red-400 rounded-lg hover:bg-port-border transition-colors"+ title="Delete snapshot"+ >+ <Trash2 size={16} />+ </button>+ )}+ </div>+ )}+ </div>+ </div>++ {/* Expanded Detail View */}+ {isViewing && viewingSnapshot && (+ <div className="bg-port-bg border border-port-border border-t-0 rounded-b-lg p-4 -mt-1">+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">+ <div>+ <h4 className="text-xs text-gray-500 uppercase tracking-wider mb-2">Metadata</h4>+ <div className="space-y-1 text-sm">+ <div><span className="text-gray-500">Created:</span> <span className="text-gray-300">{formatDate(viewingSnapshot.createdAt)}</span></div>+ <div><span className="text-gray-500">Hash:</span> <span className="text-gray-300 font-mono text-xs">{viewingSnapshot.dataHash}</span></div>+ <div><span className="text-gray-500">Size:</span> <span className="text-gray-300">{formatBytes(viewingSnapshot.sizeBytes)}</span></div>+ </div>+ </div>+ <div>+ <h4 className="text-xs text-gray-500 uppercase tracking-wider mb-2">Contents</h4>+ <div className="space-y-1 text-sm">+ <div><span className="text-gray-500">Documents:</span> <span className="text-gray-300">{viewingSnapshot.summary?.documentCount} ({viewingSnapshot.summary?.enabledDocuments} enabled)</span></div>+ <div><span className="text-gray-500">Markdown files:</span> <span className="text-gray-300">{viewingSnapshot.summary?.markdownFiles}</span></div>+ <div><span className="text-gray-500">Goals:</span> <span className="text-gray-300">{viewingSnapshot.summary?.goalsCount}</span></div>+ <div><span className="text-gray-500">Stories:</span> <span className="text-gray-300">{viewingSnapshot.summary?.storiesCount}</span></div>+ <div><span className="text-gray-500">Genome markers:</span> <span className="text-gray-300">{viewingSnapshot.summary?.genomeMarkers}</span></div>+ </div>+ </div>+ </div>++ {/* Data files included */}+ {viewingSnapshot.data && (+ <div>+ <h4 className="text-xs text-gray-500 uppercase tracking-wider mb-2">Archived Files</h4>+ <div className="flex flex-wrap gap-1.5">+ {Object.keys(viewingSnapshot.data).filter(k => k !== 'documents').map(key => (+ <span key={key} className="px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-400">+ {key}+ </span>+ ))}+ {viewingSnapshot.data.documents && Object.keys(viewingSnapshot.data.documents).map(key => (+ <span key={key} className="px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-400">+ {key}+ </span>+ ))}+ </div>+ </div>+ )}++ {/* Traits snapshot */}+ {viewingSnapshot.summary?.traits && (+ <div className="mt-4">+ <h4 className="text-xs text-gray-500 uppercase tracking-wider mb-2">Personality Traits (at time of snapshot)</h4>+ <div className="flex flex-wrap gap-2">+ {Object.entries(viewingSnapshot.summary.traits).filter(([, v]) => typeof v === 'number').map(([key, val]) => (+ <div key={key} className="bg-port-card border border-port-border rounded px-2 py-1 text-xs">+ <span className="text-gray-500">{key}:</span>{' '}+ <span className="text-gray-300">{typeof val === 'number' ? val.toFixed(1) : val}</span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}++ {/* Info Card */}+ <div className="bg-port-card rounded-lg border border-port-border p-4 text-sm text-gray-500">+ <div className="flex items-start gap-3">+ <Calendar size={16} className="mt-0.5 shrink-0 text-gray-600" />+ <div>+ <p className="text-gray-400 mb-1">Time capsules preserve a complete snapshot of your digital twin — documents, traits, goals, genome markers, autobiography stories, and test history.</p>+ <p>Create snapshots at meaningful moments to track how your identity evolves over time.</p>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsxindex 6703afd90a..0081552221 100644--- a/client/src/pages/DigitalTwin.jsx+++ b/client/src/pages/DigitalTwin.jsx@@ -17,6 +17,7 @@ import GoalsTab from '../components/digital-twin/tabs/GoalsTab';import AutobiographyTab from '../components/digital-twin/tabs/AutobiographyTab';import ImportTab from '../components/digital-twin/tabs/ImportTab';import ExportTab from '../components/digital-twin/tabs/ExportTab';+import TimeCapsuleTab from '../components/digital-twin/tabs/TimeCapsuleTab';export default function DigitalTwin() {const { tab } = useParams();@@ -73,6 +74,8 @@ export default function DigitalTwin() {return <ImportTab onRefresh={fetchData} />;case 'export':return <ExportTab onRefresh={fetchData} />;+ case 'time-capsule':+ return <TimeCapsuleTab onRefresh={fetchData} />;default:return <OverviewTab status={status} settings={settings} onRefresh={fetchData} />;}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex a7aa3060e3..e128bb2fdb 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1312,6 +1312,21 @@ export const deleteSocialAccount = (id) => request(`/digital-twin/social-accountmethod: 'DELETE'});+// Digital Twin - Time Capsule Snapshots+export const listTimeCapsuleSnapshots = () => request('/digital-twin/snapshots');+export const createTimeCapsuleSnapshot = (label, description = '') => request('/digital-twin/snapshots', {+ method: 'POST',+ body: JSON.stringify({ label, description })+});+export const getTimeCapsuleSnapshot = (id) => request(`/digital-twin/snapshots/${id}`);+export const deleteTimeCapsuleSnapshot = (id) => request(`/digital-twin/snapshots/${id}`, {+ method: 'DELETE'+});+export const compareTimeCapsuleSnapshots = (id1, id2) => request('/digital-twin/snapshots/compare', {+ method: 'POST',+ body: JSON.stringify({ id1, id2 })+});+// MeatSpace - Genomeexport const getGenomeSummary = () => request('/meatspace/genome');export const uploadGenomeFile = (content, filename) => request('/meatspace/genome/upload', {diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex 5c1de7ac43..65f5b57fe0 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -445,3 +445,17 @@ export const feedbackInputSchema = z.object({model: z.string().min(1).optional(),documentsUsed: z.array(z.string()).optional()});++// =============================================================================+// TIME CAPSULE SCHEMAS+// =============================================================================++export const createSnapshotInputSchema = z.object({+ label: z.string().min(1).max(200),+ description: z.string().max(1000).optional().default('')+});++export const compareSnapshotsInputSchema = z.object({+ id1: z.string().uuid(),+ id2: z.string().uuid()+});diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.jsindex 87208b3b42..76eb5efd5c 100644--- a/server/routes/digital-twin.js+++ b/server/routes/digital-twin.js@@ -40,8 +40,11 @@ import {tasteSummaryInputSchema,tasteSectionEnum,tastePersonalizedQuestionInputSchema,- feedbackInputSchema+ feedbackInputSchema,+ createSnapshotInputSchema,+ compareSnapshotsInputSchema} from '../lib/digitalTwinValidation.js';+import * as timeCapsuleService from '../services/timeCapsule.js';const router = Router();@@ -634,4 +637,64 @@ router.delete('/taste/:section', asyncHandler(async (req, res) => {res.json(result);}));+// =============================================================================+// TIME CAPSULE SNAPSHOTS+// =============================================================================++/**+ * GET /api/digital-twin/snapshots+ * List all time capsule snapshots (metadata only)+ */+router.get('/snapshots', asyncHandler(async (req, res) => {+ const snapshots = await timeCapsuleService.listSnapshots();+ res.json(snapshots);+}));++/**+ * POST /api/digital-twin/snapshots+ * Create a new time capsule snapshot+ */+router.post('/snapshots', asyncHandler(async (req, res) => {+ const data = validateRequest(createSnapshotInputSchema, req.body);+ const snapshot = await timeCapsuleService.createSnapshot(data.label, data.description);+ res.status(201).json(snapshot);+}));++/**+ * GET /api/digital-twin/snapshots/:id+ * Get a snapshot with full data+ */+router.get('/snapshots/:id', asyncHandler(async (req, res) => {+ const snapshot = await timeCapsuleService.getSnapshot(req.params.id);+ if (!snapshot) {+ throw new ServerError('Snapshot not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(snapshot);+}));++/**+ * DELETE /api/digital-twin/snapshots/:id+ * Delete a snapshot+ */+router.delete('/snapshots/:id', asyncHandler(async (req, res) => {+ const deleted = await timeCapsuleService.deleteSnapshot(req.params.id);+ if (!deleted) {+ throw new ServerError('Snapshot not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json({ success: true });+}));++/**+ * POST /api/digital-twin/snapshots/compare+ * Compare two snapshots+ */+router.post('/snapshots/compare', asyncHandler(async (req, res) => {+ const data = validateRequest(compareSnapshotsInputSchema, req.body);+ const diff = await timeCapsuleService.compareSnapshots(data.id1, data.id2);+ if (!diff) {+ throw new ServerError('One or both snapshots not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(diff);+}));+export default router;diff --git a/server/services/timeCapsule.js b/server/services/timeCapsule.jsnew file mode 100644index 0000000000..aa0a2944db--- /dev/null+++ b/server/services/timeCapsule.js@@ -0,0 +1,224 @@+/**+ * Time Capsule Service+ *+ * Creates versioned snapshots of digital twin data for historical preservation.+ * Supports creating, listing, viewing, comparing, and deleting snapshots.+ */++import { readFile, writeFile, unlink, readdir, stat } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { createHash } from 'crypto';+import { v4 as uuidv4 } from 'uuid';+import { ensureDir, PATHS } from '../lib/fileUtils.js';++const DIGITAL_TWIN_DIR = PATHS.digitalTwin;+const SNAPSHOTS_DIR = join(DIGITAL_TWIN_DIR, 'snapshots');+const INDEX_FILE = join(SNAPSHOTS_DIR, 'index.json');++async function ensureSnapshotsDir() {+ await ensureDir(SNAPSHOTS_DIR);+}++async function loadIndex() {+ await ensureSnapshotsDir();+ if (!existsSync(INDEX_FILE)) {+ return { snapshots: [] };+ }+ const raw = await readFile(INDEX_FILE, 'utf-8');+ return JSON.parse(raw);+}++async function saveIndex(index) {+ await ensureSnapshotsDir();+ await writeFile(INDEX_FILE, JSON.stringify(index, null, 2));+}++/**+ * Collect all digital twin data files into a single snapshot payload+ */+async function collectTwinData() {+ const files = {};+ const jsonFiles = ['meta.json', 'identity.json', 'goals.json', 'taste-profile.json',+ 'feedback.json', 'genome.json', 'longevity.json', 'chronotype.json'];++ for (const filename of jsonFiles) {+ const filePath = join(DIGITAL_TWIN_DIR, filename);+ if (existsSync(filePath)) {+ const content = await readFile(filePath, 'utf-8');+ files[filename] = JSON.parse(content);+ }+ }++ // Collect autobiography stories+ const storiesPath = join(DIGITAL_TWIN_DIR, 'autobiography', 'stories.json');+ if (existsSync(storiesPath)) {+ const content = await readFile(storiesPath, 'utf-8');+ files['autobiography/stories.json'] = JSON.parse(content);+ }++ // Collect all markdown documents+ const mdFiles = {};+ const entries = await readdir(DIGITAL_TWIN_DIR).catch(() => []);+ for (const entry of entries) {+ if (entry.endsWith('.md')) {+ const filePath = join(DIGITAL_TWIN_DIR, entry);+ const info = await stat(filePath);+ if (info.isFile()) {+ mdFiles[entry] = await readFile(filePath, 'utf-8');+ }+ }+ }+ if (Object.keys(mdFiles).length > 0) {+ files.documents = mdFiles;+ }++ return files;+}++/**+ * Build summary metadata from collected data+ */+function buildSummary(data) {+ const meta = data['meta.json'] || {};+ const docs = meta.documents || [];+ const goals = data['goals.json'];+ const stories = data['autobiography/stories.json'];+ const genome = data['genome.json'];+ const identity = data['identity.json'];+ const mdDocs = data.documents || {};++ return {+ documentCount: docs.length,+ enabledDocuments: docs.filter(d => d.enabled).length,+ markdownFiles: Object.keys(mdDocs).length,+ goalsCount: Array.isArray(goals?.goals) ? goals.goals.length : 0,+ storiesCount: Array.isArray(stories) ? stories.length : 0,+ genomeMarkers: Array.isArray(genome?.markers) ? genome.markers.length : 0,+ hasIdentity: !!identity,+ testHistoryCount: Array.isArray(meta.testHistory) ? meta.testHistory.length : 0,+ traits: meta.traits || null,+ confidenceScores: meta.confidenceScores || null+ };+}++/**+ * Create a new time capsule snapshot+ */+export async function createSnapshot(label, description = '') {+ const data = await collectTwinData();+ const dataString = JSON.stringify(data);+ const dataHash = createHash('sha256').update(dataString).digest('hex').slice(0, 16);++ const snapshot = {+ id: uuidv4(),+ label,+ description,+ createdAt: new Date().toISOString(),+ dataHash,+ sizeBytes: Buffer.byteLength(dataString, 'utf-8'),+ summary: buildSummary(data)+ };++ // Save snapshot data+ const snapshotFile = join(SNAPSHOTS_DIR, `${snapshot.id}.json`);+ await writeFile(snapshotFile, JSON.stringify({ ...snapshot, data }, null, 2));++ // Update index+ const index = await loadIndex();+ index.snapshots.unshift(snapshot);+ await saveIndex(index);++ console.log(`📸 Time capsule created: "${label}" (${snapshot.id.slice(0, 8)})`);+ return snapshot;+}++/**+ * List all snapshots (metadata only, no data)+ */+export async function listSnapshots() {+ const index = await loadIndex();+ return index.snapshots;+}++/**+ * Get a single snapshot with full data+ */+export async function getSnapshot(id) {+ const snapshotFile = join(SNAPSHOTS_DIR, `${id}.json`);+ if (!existsSync(snapshotFile)) return null;+ const raw = await readFile(snapshotFile, 'utf-8');+ return JSON.parse(raw);+}++/**+ * Delete a snapshot+ */+export async function deleteSnapshot(id) {+ const index = await loadIndex();+ const exists = index.snapshots.find(s => s.id === id);+ if (!exists) return false;++ const snapshotFile = join(SNAPSHOTS_DIR, `${id}.json`);+ if (existsSync(snapshotFile)) {+ await unlink(snapshotFile);+ }++ index.snapshots = index.snapshots.filter(s => s.id !== id);+ await saveIndex(index);++ console.log(`🗑️ Time capsule deleted: "${exists.label}" (${id.slice(0, 8)})`);+ return true;+}++/**+ * Compare two snapshots and return differences+ */+export async function compareSnapshots(id1, id2) {+ const [snap1, snap2] = await Promise.all([getSnapshot(id1), getSnapshot(id2)]);+ if (!snap1 || !snap2) return null;++ const diff = {+ snapshot1: { id: snap1.id, label: snap1.label, createdAt: snap1.createdAt },+ snapshot2: { id: snap2.id, label: snap2.label, createdAt: snap2.createdAt },+ changes: []+ };++ // Compare document counts+ const s1 = snap1.summary;+ const s2 = snap2.summary;++ const fields = [+ ['documentCount', 'Documents'],+ ['enabledDocuments', 'Enabled documents'],+ ['markdownFiles', 'Markdown files'],+ ['goalsCount', 'Goals'],+ ['storiesCount', 'Autobiography stories'],+ ['genomeMarkers', 'Genome markers'],+ ['testHistoryCount', 'Test runs']+ ];++ for (const [key, label] of fields) {+ if (s1[key] !== s2[key]) {+ diff.changes.push({ field: label, before: s1[key], after: s2[key] });+ }+ }++ // Compare markdown document lists+ const docs1 = Object.keys(snap1.data?.documents || {}).sort();+ const docs2 = Object.keys(snap2.data?.documents || {}).sort();+ const added = docs2.filter(d => !docs1.includes(d));+ const removed = docs1.filter(d => !docs2.includes(d));+ const modified = docs1.filter(d => docs2.includes(d) && snap1.data.documents[d] !== snap2.data.documents[d]);++ if (added.length > 0) diff.changes.push({ field: 'Documents added', value: added });+ if (removed.length > 0) diff.changes.push({ field: 'Documents removed', value: removed });+ if (modified.length > 0) diff.changes.push({ field: 'Documents modified', value: modified });++ // Compare traits+ if (JSON.stringify(s1.traits) !== JSON.stringify(s2.traits)) {+ diff.changes.push({ field: 'Traits', before: s1.traits, after: s2.traits });+ }++ return diff;+}