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: add mortality-aware goal tracking with longevity derivation (M42 P3)
Adam Eivy415f5326f6eb
diff --git a/.changelog/v1.7.x.md b/.changelog/v1.7.x.mdindex a475e95386..5c2a0d31a4 100644--- a/.changelog/v1.7.x.md+++ b/.changelog/v1.7.x.md@@ -4,7 +4,7 @@ Released: YYYY-MM-DD## Overview-Personalized taste prompting, behavioral feedback loop, and expanded aesthetic domains for the Digital Twin.+Personalized taste prompting, behavioral feedback loop, mortality-aware goal tracking, and expanded aesthetic domains for the Digital Twin.## Features@@ -27,3 +27,14 @@ Personalized taste prompting, behavioral feedback loop, and expanded aesthetic d- Feedback statistics dashboard in TestTab: total ratings, validation rate percentage, per-validation breakdown, and recent accuracy trend (improving/declining/stable)- Document weight recalculation from feedback history — documents consistently associated with validated responses get boosted, contradicted ones get reduced- New API endpoints: `POST /api/digital-twin/feedback`, `GET /api/digital-twin/feedback/stats`, `POST /api/digital-twin/feedback/recalculate`, `GET /api/digital-twin/feedback/recent`++### Mortality-Aware Goal Tracking (M42 P3)+- **Longevity derivation**: Extracts 5 longevity markers (FOXO3A, IGF1R, CETP, IPMK, TERC) and 6 cardiovascular markers (Factor V, CAD 9p21, LPA, Prothrombin, IL-6, TNF-alpha) from genome data+- **Life expectancy estimation**: SSA actuarial baseline (78.5y) adjusted by genome marker signals — longevity markers add/subtract up to 5 years, cardiovascular risk adjusts up to 4 years+- **Time horizons**: Age, years remaining, healthy years remaining (85% estimate), and percent life complete — calculated from birth date + adjusted life expectancy+- **Goal CRUD with urgency scoring**: Create goals with title, description, time horizon (1y/3y/5y/10y/20y/lifetime), and category (creative/family/health/financial/legacy/mastery). Urgency auto-calculated from remaining life years relative to goal horizon+- **Milestone tracking**: Add milestones with optional target dates, mark complete individually, progress bar on goal cards+- **Goals Tab UI**: New "Goals" tab in Digital Twin with life expectancy dashboard (4-stat grid), goal list with expandable detail, milestone management, genome marker detail view, and completed goals section+- **Identity status extended**: Longevity and goals sections added to identity orchestrator status+- New API endpoints: `GET/POST /api/digital-twin/identity/longevity`, `GET/POST/PUT/DELETE /api/digital-twin/identity/goals`, `PUT /api/digital-twin/identity/goals/birth-date`, milestone CRUD+- 38 new tests (1143 total) covering marker extraction, life expectancy computation, urgency scoring, and goal CRUDdiff --git a/PLAN.md b/PLAN.mdindex e2f1ddb737..f687c1f793 100644--- a/PLAN.md+++ b/PLAN.md@@ -74,8 +74,8 @@ pm2 logs### Planned-- [ ] **M34 P3,P5-P7**: Digital Twin - Behavioral feedback loop, multi-modal capture, advanced testing, personas-- [ ] **M42**: Unified Digital Twin Identity System - See [Identity System](./docs/features/identity-system.md)+- [ ] **M34 P5-P7**: Digital Twin - Multi-modal capture, advanced testing, personas+- [ ] **M42 P4-P5**: Unified Digital Twin Identity System - Identity Tab UI, Cross-Insights Engine. See [Identity System](./docs/features/identity-system.md)---@@ -162,4 +162,4 @@ All 10 audit items (S1–S10) from the 2025-02-19 security audit have been resol2. ~~**M42 P2.5: Personalized Taste Prompting**~~ ✅ - LLM-personalized follow-ups using identity context, 2 new taste sections (Fashion & Digital), "Go Deeper" flow3. **M7: App Templates** - Implement template management UI and app scaffolding from templates4. ~~**M34 P3: Behavioral Feedback Loop**~~ ✅ - "Sounds like me" validation on test responses and taste summaries, feedback stats dashboard, document weight recalculation-5. **M42 P3: Mortality-Aware Goal Tracking** - Birth date + genome longevity markers for urgency-scored goals+5. ~~**M42 P3: Mortality-Aware Goal Tracking**~~ ✅ - Longevity/cardiovascular marker extraction, life expectancy estimation, goal CRUD with urgency scoring, Goals tab UI, 38 new testsdiff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.jsindex 75309fd348..2680291a40 100644--- a/client/src/components/digital-twin/constants.js+++ b/client/src/components/digital-twin/constants.js@@ -25,7 +25,8 @@ import {Fingerprint,Globe,Dna,- PenLine+ PenLine,+ Target} from 'lucide-react';// Main navigation tabs@@ -37,6 +38,7 @@ export const TABS = [{ id: 'taste', label: 'Taste', icon: Palette },{ id: 'accounts', label: 'Accounts', icon: Globe },{ id: 'genome', label: 'Genome', icon: Dna },+ { id: 'goals', label: 'Goals', icon: Target },{ id: 'interview', label: 'Interview', icon: MessageSquare },{ id: 'autobiography', label: 'Autobiography', icon: PenLine },{ id: 'import', label: 'Import', icon: Upload },diff --git a/client/src/components/digital-twin/tabs/GoalsTab.jsx b/client/src/components/digital-twin/tabs/GoalsTab.jsxnew file mode 100644index 0000000000..404418aeae--- /dev/null+++ b/client/src/components/digital-twin/tabs/GoalsTab.jsx@@ -0,0 +1,564 @@+import { useState, useEffect, useCallback } from 'react';+import {+ Target, Plus, Trash2, Check, ChevronDown, ChevronUp,+ Calendar, Heart, DollarSign, Lightbulb, Users, Flame,+ Clock, AlertTriangle, Activity, RefreshCw, Milestone+} from 'lucide-react';+import * as api from '../../../services/api';++const CATEGORY_CONFIG = {+ creative: { label: 'Creative', icon: Lightbulb, color: 'text-purple-400', bg: 'bg-purple-500/20' },+ family: { label: 'Family', icon: Users, color: 'text-pink-400', bg: 'bg-pink-500/20' },+ health: { label: 'Health', icon: Heart, color: 'text-green-400', bg: 'bg-green-500/20' },+ financial: { label: 'Financial', icon: DollarSign, color: 'text-yellow-400', bg: 'bg-yellow-500/20' },+ legacy: { label: 'Legacy', icon: Flame, color: 'text-orange-400', bg: 'bg-orange-500/20' },+ mastery: { label: 'Mastery', icon: Target, color: 'text-blue-400', bg: 'bg-blue-500/20' }+};++const HORIZON_OPTIONS = [+ { value: '1-year', label: '1 Year' },+ { value: '3-year', label: '3 Years' },+ { value: '5-year', label: '5 Years' },+ { value: '10-year', label: '10 Years' },+ { value: '20-year', label: '20 Years' },+ { value: 'lifetime', label: 'Lifetime' }+];++function urgencyColor(urgency) {+ if (urgency == null) return 'text-gray-500';+ if (urgency >= 0.7) return 'text-red-400';+ if (urgency >= 0.4) return 'text-yellow-400';+ return 'text-green-400';+}++function urgencyLabel(urgency) {+ if (urgency == null) return 'Unknown';+ if (urgency >= 0.7) return 'Urgent';+ if (urgency >= 0.4) return 'Moderate';+ return 'Low';+}++export default function GoalsTab({ onRefresh }) {+ const [goalsData, setGoalsData] = useState(null);+ const [longevity, setLongevity] = useState(null);+ const [loading, setLoading] = useState(true);+ const [expandedGoal, setExpandedGoal] = useState(null);+ const [showNewGoal, setShowNewGoal] = useState(false);+ const [showBirthDate, setShowBirthDate] = useState(false);+ const [newGoal, setNewGoal] = useState({ title: '', description: '', horizon: '5-year', category: 'mastery' });+ const [birthDateInput, setBirthDateInput] = useState('');+ const [newMilestone, setNewMilestone] = useState({ title: '', targetDate: '' });+ const [derivingLongevity, setDerivingLongevity] = useState(false);++ const loadData = useCallback(async () => {+ const [goals, longevityData] = await Promise.all([+ api.getGoals().catch(() => null),+ api.getLongevity().catch(() => null)+ ]);+ setGoalsData(goals);+ setLongevity(longevityData);+ if (goals?.birthDate) setBirthDateInput(goals.birthDate);+ setLoading(false);+ }, []);++ useEffect(() => { loadData(); }, [loadData]);++ const handleSetBirthDate = async () => {+ if (!birthDateInput) return;+ await api.setBirthDate(birthDateInput);+ setShowBirthDate(false);+ await loadData();+ onRefresh?.();+ };++ const handleDeriveLongevity = async () => {+ setDerivingLongevity(true);+ await api.deriveLongevity();+ setDerivingLongevity(false);+ await loadData();+ };++ const handleCreateGoal = async () => {+ if (!newGoal.title.trim()) return;+ await api.createGoal(newGoal);+ setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery' });+ setShowNewGoal(false);+ await loadData();+ onRefresh?.();+ };++ const handleUpdateGoalStatus = async (goalId, status) => {+ await api.updateGoal(goalId, { status });+ await loadData();+ };++ const handleDeleteGoal = async (goalId) => {+ await api.deleteGoal(goalId);+ setExpandedGoal(null);+ await loadData();+ onRefresh?.();+ };++ const handleAddMilestone = async (goalId) => {+ if (!newMilestone.title.trim()) return;+ await api.addGoalMilestone(goalId, {+ title: newMilestone.title,+ ...(newMilestone.targetDate ? { targetDate: newMilestone.targetDate } : {})+ });+ setNewMilestone({ title: '', targetDate: '' });+ await loadData();+ };++ const handleCompleteMilestone = async (goalId, milestoneId) => {+ await api.completeGoalMilestone(goalId, milestoneId);+ await loadData();+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center py-20">+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />+ </div>+ );+ }++ const activeGoals = goalsData?.goals?.filter(g => g.status === 'active') || [];+ const completedGoals = goalsData?.goals?.filter(g => g.status === 'completed') || [];+ const hasBirthDate = !!goalsData?.birthDate;+ const hasLongevity = !!longevity?.derivedAt;+ const timeHorizons = longevity?.timeHorizons;++ return (+ <div className="space-y-6">+ {/* Life Expectancy Card */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-2">+ <Activity className="w-5 h-5 text-port-accent" />+ <h3 className="font-medium text-white">Life Expectancy</h3>+ </div>+ <div className="flex gap-2">+ {hasBirthDate && (+ <button+ onClick={handleDeriveLongevity}+ disabled={derivingLongevity}+ className="text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 disabled:opacity-50"+ >+ {derivingLongevity ? 'Deriving...' : 'Re-derive'}+ </button>+ )}+ <button+ onClick={() => setShowBirthDate(!showBirthDate)}+ className="text-xs px-2 py-1 rounded bg-port-border text-gray-300 hover:bg-gray-600"+ >+ {hasBirthDate ? 'Update Birth Date' : 'Set Birth Date'}+ </button>+ </div>+ </div>++ {showBirthDate && (+ <div className="flex gap-2 mb-3">+ <input+ type="date"+ value={birthDateInput}+ onChange={e => setBirthDateInput(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"+ />+ <button+ onClick={handleSetBirthDate}+ className="px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-blue-600"+ >+ Save+ </button>+ </div>+ )}++ {!hasBirthDate ? (+ <p className="text-sm text-gray-500">+ Set your birth date to enable mortality-aware goal urgency scoring. Your genome longevity and cardiovascular markers will adjust your estimated life expectancy.+ </p>+ ) : hasLongevity ? (+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">+ <div className="bg-port-bg rounded-lg p-3 text-center">+ <div className="text-2xl font-bold text-white">+ {longevity.lifeExpectancy.adjusted}+ </div>+ <div className="text-xs text-gray-500">Adjusted Life Expectancy</div>+ <div className="text-xs text-gray-600 mt-1">+ Baseline: {longevity.lifeExpectancy.baseline}+ {longevity.lifeExpectancy.longevityAdjustment !== 0 && (+ <span className={longevity.lifeExpectancy.longevityAdjustment > 0 ? 'text-green-500' : 'text-red-500'}>+ {' '}{longevity.lifeExpectancy.longevityAdjustment > 0 ? '+' : ''}{longevity.lifeExpectancy.longevityAdjustment} longevity+ </span>+ )}+ {longevity.lifeExpectancy.cardiovascularAdjustment !== 0 && (+ <span className={longevity.lifeExpectancy.cardiovascularAdjustment > 0 ? 'text-green-500' : 'text-red-500'}>+ {' '}{longevity.lifeExpectancy.cardiovascularAdjustment > 0 ? '+' : ''}{longevity.lifeExpectancy.cardiovascularAdjustment} cardio+ </span>+ )}+ </div>+ </div>++ {timeHorizons && (+ <>+ <div className="bg-port-bg rounded-lg p-3 text-center">+ <div className="text-2xl font-bold text-white">{timeHorizons.ageYears}</div>+ <div className="text-xs text-gray-500">Current Age</div>+ </div>+ <div className="bg-port-bg rounded-lg p-3 text-center">+ <div className="text-2xl font-bold text-green-400">{timeHorizons.yearsRemaining}</div>+ <div className="text-xs text-gray-500">Years Remaining</div>+ <div className="text-xs text-gray-600 mt-1">{timeHorizons.healthyYearsRemaining} healthy</div>+ </div>+ <div className="bg-port-bg rounded-lg p-3 text-center">+ <div className="text-2xl font-bold text-amber-400">{timeHorizons.percentLifeComplete}%</div>+ <div className="text-xs text-gray-500">Life Complete</div>+ <div className="w-full bg-gray-700 rounded-full h-1.5 mt-2">+ <div+ className="bg-amber-400 h-1.5 rounded-full transition-all"+ style={{ width: `${Math.min(100, timeHorizons.percentLifeComplete)}%` }}+ />+ </div>+ </div>+ </>+ )}+ </div>+ ) : (+ <div className="flex items-center gap-2 text-sm text-gray-500">+ <Clock className="w-4 h-4" />+ Birth date set. Click "Re-derive" to calculate life expectancy from genome markers.+ </div>+ )}++ {hasLongevity && (+ <div className="mt-3 flex gap-4 text-xs text-gray-500">+ <span>+ Longevity markers: {Object.keys(longevity.longevityMarkers || {}).length}/{5}+ </span>+ <span>+ Cardiovascular markers: {Object.keys(longevity.cardiovascularMarkers || {}).length}/{6}+ </span>+ <span>+ Confidence: {Math.round((longevity.confidence || 0) * 100)}%+ </span>+ </div>+ )}+ </div>++ {/* Goals Section */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between mb-4">+ <div className="flex items-center gap-2">+ <Target className="w-5 h-5 text-port-accent" />+ <h3 className="font-medium text-white">+ Goals ({activeGoals.length} active)+ </h3>+ </div>+ <button+ onClick={() => setShowNewGoal(!showNewGoal)}+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-blue-600"+ >+ <Plus className="w-4 h-4" />+ Add Goal+ </button>+ </div>++ {/* New Goal Form */}+ {showNewGoal && (+ <div className="bg-port-bg border border-port-border rounded-lg p-4 mb-4 space-y-3">+ <input+ type="text"+ value={newGoal.title}+ onChange={e => setNewGoal({ ...newGoal, title: e.target.value })}+ placeholder="Goal title..."+ className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-500"+ />+ <textarea+ value={newGoal.description}+ onChange={e => setNewGoal({ ...newGoal, description: e.target.value })}+ placeholder="Description (optional)..."+ rows={2}+ className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-500 resize-none"+ />+ <div className="flex gap-3">+ <div className="flex-1">+ <label className="block text-xs text-gray-500 mb-1">Horizon</label>+ <select+ value={newGoal.horizon}+ onChange={e => setNewGoal({ ...newGoal, horizon: e.target.value })}+ className="w-full bg-port-card border border-port-border rounded px-3 py-1.5 text-sm text-white"+ >+ {HORIZON_OPTIONS.map(h => (+ <option key={h.value} value={h.value}>{h.label}</option>+ ))}+ </select>+ </div>+ <div className="flex-1">+ <label className="block text-xs text-gray-500 mb-1">Category</label>+ <select+ value={newGoal.category}+ onChange={e => setNewGoal({ ...newGoal, category: e.target.value })}+ className="w-full bg-port-card border border-port-border rounded px-3 py-1.5 text-sm text-white"+ >+ {Object.entries(CATEGORY_CONFIG).map(([key, cfg]) => (+ <option key={key} value={key}>{cfg.label}</option>+ ))}+ </select>+ </div>+ </div>+ <div className="flex gap-2">+ <button+ onClick={handleCreateGoal}+ disabled={!newGoal.title.trim()}+ className="px-4 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-blue-600 disabled:opacity-50"+ >+ Create+ </button>+ <button+ onClick={() => setShowNewGoal(false)}+ className="px-4 py-1.5 text-sm rounded bg-port-border text-gray-300 hover:bg-gray-600"+ >+ Cancel+ </button>+ </div>+ </div>+ )}++ {/* Active Goals */}+ {activeGoals.length === 0 ? (+ <p className="text-sm text-gray-500 py-4 text-center">+ No goals yet. Add your first goal to start tracking with mortality-aware urgency scoring.+ </p>+ ) : (+ <div className="space-y-2">+ {activeGoals.map(goal => {+ const cat = CATEGORY_CONFIG[goal.category] || CATEGORY_CONFIG.mastery;+ const CatIcon = cat.icon;+ const isExpanded = expandedGoal === goal.id;+ const completedMs = goal.milestones?.filter(m => m.completedAt) || [];+ const totalMs = goal.milestones?.length || 0;++ return (+ <div key={goal.id} className="bg-port-bg border border-port-border rounded-lg">+ <button+ onClick={() => setExpandedGoal(isExpanded ? null : goal.id)}+ className="w-full flex items-center gap-3 p-3 text-left"+ >+ <div className={`p-1.5 rounded ${cat.bg}`}>+ <CatIcon className={`w-4 h-4 ${cat.color}`} />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium text-white truncate">{goal.title}</span>+ <span className="text-xs text-gray-500 flex-shrink-0">+ {HORIZON_OPTIONS.find(h => h.value === goal.horizon)?.label}+ </span>+ </div>+ {totalMs > 0 && (+ <div className="flex items-center gap-1 mt-0.5">+ <div className="w-16 bg-gray-700 rounded-full h-1">+ <div+ className="bg-port-accent h-1 rounded-full"+ style={{ width: `${totalMs > 0 ? (completedMs.length / totalMs) * 100 : 0}%` }}+ />+ </div>+ <span className="text-xs text-gray-500">{completedMs.length}/{totalMs}</span>+ </div>+ )}+ </div>+ <div className="flex items-center gap-2 flex-shrink-0">+ {goal.urgency != null && (+ <div className={`flex items-center gap-1 ${urgencyColor(goal.urgency)}`}>+ {goal.urgency >= 0.7 && <AlertTriangle className="w-3.5 h-3.5" />}+ <span className="text-xs font-medium">{urgencyLabel(goal.urgency)}</span>+ </div>+ )}+ {isExpanded ? <ChevronUp className="w-4 h-4 text-gray-500" /> : <ChevronDown className="w-4 h-4 text-gray-500" />}+ </div>+ </button>++ {isExpanded && (+ <div className="px-3 pb-3 space-y-3 border-t border-port-border pt-3">+ {goal.description && (+ <p className="text-sm text-gray-400">{goal.description}</p>+ )}++ <div className="flex flex-wrap gap-2 text-xs text-gray-500">+ <span className={`px-2 py-0.5 rounded ${cat.bg} ${cat.color}`}>{cat.label}</span>+ {goal.urgency != null && (+ <span className={`px-2 py-0.5 rounded bg-gray-700 ${urgencyColor(goal.urgency)}`}>+ Urgency: {Math.round(goal.urgency * 100)}%+ </span>+ )}+ <span className="px-2 py-0.5 rounded bg-gray-700 text-gray-400">+ Created {new Date(goal.createdAt).toLocaleDateString()}+ </span>+ </div>++ {/* Milestones */}+ <div>+ <div className="flex items-center gap-1 mb-2">+ <Milestone className="w-3.5 h-3.5 text-gray-500" />+ <span className="text-xs font-medium text-gray-400">Milestones</span>+ </div>+ {goal.milestones?.length > 0 ? (+ <div className="space-y-1">+ {goal.milestones.map(ms => (+ <div key={ms.id} className="flex items-center gap-2 text-sm">+ <button+ onClick={() => !ms.completedAt && handleCompleteMilestone(goal.id, ms.id)}+ className={`w-4 h-4 rounded border flex items-center justify-center flex-shrink-0 ${+ ms.completedAt+ ? 'bg-green-500/20 border-green-500 text-green-400'+ : 'border-gray-600 hover:border-port-accent'+ }`}+ >+ {ms.completedAt && <Check className="w-3 h-3" />}+ </button>+ <span className={ms.completedAt ? 'text-gray-500 line-through' : 'text-gray-300'}>+ {ms.title}+ </span>+ {ms.targetDate && (+ <span className="text-xs text-gray-600 ml-auto">+ {new Date(ms.targetDate).toLocaleDateString()}+ </span>+ )}+ </div>+ ))}+ </div>+ ) : (+ <p className="text-xs text-gray-600">No milestones yet</p>+ )}++ {/* Add milestone */}+ <div className="flex gap-2 mt-2">+ <input+ type="text"+ value={newMilestone.title}+ onChange={e => setNewMilestone({ ...newMilestone, title: e.target.value })}+ placeholder="Add milestone..."+ className="flex-1 bg-port-card border border-port-border rounded px-2 py-1 text-xs text-white placeholder-gray-600"+ onKeyDown={e => e.key === 'Enter' && handleAddMilestone(goal.id)}+ />+ <input+ type="date"+ value={newMilestone.targetDate}+ onChange={e => setNewMilestone({ ...newMilestone, targetDate: e.target.value })}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-xs text-white w-32"+ />+ <button+ onClick={() => handleAddMilestone(goal.id)}+ disabled={!newMilestone.title.trim()}+ className="px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 disabled:opacity-50"+ >+ Add+ </button>+ </div>+ </div>++ {/* Actions */}+ <div className="flex gap-2 pt-1">+ <button+ onClick={() => handleUpdateGoalStatus(goal.id, 'completed')}+ className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-green-500/20 text-green-400 hover:bg-green-500/30"+ >+ <Check className="w-3 h-3" />+ Complete+ </button>+ <button+ onClick={() => handleDeleteGoal(goal.id)}+ className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-red-500/20 text-red-400 hover:bg-red-500/30"+ >+ <Trash2 className="w-3 h-3" />+ Delete+ </button>+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>++ {/* Completed Goals */}+ {completedGoals.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="font-medium text-gray-400 mb-3 flex items-center gap-2">+ <Check className="w-4 h-4 text-green-400" />+ Completed ({completedGoals.length})+ </h3>+ <div className="space-y-1">+ {completedGoals.map(goal => {+ const cat = CATEGORY_CONFIG[goal.category] || CATEGORY_CONFIG.mastery;+ const CatIcon = cat.icon;+ return (+ <div key={goal.id} className="flex items-center gap-2 py-1.5 text-sm">+ <CatIcon className={`w-4 h-4 ${cat.color} opacity-50`} />+ <span className="text-gray-500 line-through">{goal.title}</span>+ <span className="text-xs text-gray-600 ml-auto">+ {HORIZON_OPTIONS.find(h => h.value === goal.horizon)?.label}+ </span>+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Longevity Markers Detail (collapsed) */}+ {hasLongevity && (+ <details className="bg-port-card border border-port-border rounded-lg">+ <summary className="p-4 cursor-pointer text-sm font-medium text-gray-400 hover:text-white">+ Genome Marker Details+ </summary>+ <div className="px-4 pb-4 space-y-3">+ {Object.keys(longevity.longevityMarkers || {}).length > 0 && (+ <div>+ <h4 className="text-xs font-medium text-gray-500 mb-2">Longevity Markers</h4>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ {Object.entries(longevity.longevityMarkers).map(([name, marker]) => (+ <div key={name} className="flex items-center justify-between bg-port-bg rounded px-3 py-2 text-xs">+ <div>+ <span className="text-white font-medium">{marker.gene}</span>+ <span className="text-gray-500 ml-1">({marker.rsid})</span>+ </div>+ <span className={+ marker.status === 'beneficial' ? 'text-green-400' :+ marker.status === 'concern' ? 'text-red-400' : 'text-gray-400'+ }>+ {marker.genotype} — {marker.status}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}+ {Object.keys(longevity.cardiovascularMarkers || {}).length > 0 && (+ <div>+ <h4 className="text-xs font-medium text-gray-500 mb-2">Cardiovascular Markers</h4>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ {Object.entries(longevity.cardiovascularMarkers).map(([name, marker]) => (+ <div key={name} className="flex items-center justify-between bg-port-bg rounded px-3 py-2 text-xs">+ <div>+ <span className="text-white font-medium">{marker.gene}</span>+ <span className="text-gray-500 ml-1">({marker.rsid})</span>+ </div>+ <span className={+ marker.status === 'beneficial' ? 'text-green-400' :+ marker.status === 'concern' || marker.status === 'major_concern' ? 'text-red-400' : 'text-gray-400'+ }>+ {marker.genotype} — {marker.status}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ </details>+ )}+ </div>+ );+}diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsxindex aa05ea5a7a..86e623d96b 100644--- a/client/src/pages/DigitalTwin.jsx+++ b/client/src/pages/DigitalTwin.jsx@@ -13,6 +13,7 @@ import TasteTab from '../components/digital-twin/tabs/TasteTab';import AccountsTab from '../components/digital-twin/tabs/AccountsTab';import InterviewTab from '../components/digital-twin/tabs/InterviewTab';import GenomeTab from '../components/digital-twin/tabs/GenomeTab';+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';@@ -62,6 +63,8 @@ export default function DigitalTwin() {return <AccountsTab />;case 'genome':return <GenomeTab />;+ case 'goals':+ return <GoalsTab onRefresh={fetchData} />;case 'interview':return <InterviewTab onRefresh={fetchData} />;case 'autobiography':diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 63ae36f95c..7d3b5b0846 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1228,6 +1228,37 @@ export const deleteEpigeneticIntervention = (id) => request(`/digital-twin/genommethod: 'DELETE'});+// Digital Twin - Identity+export const getIdentityStatus = () => request('/digital-twin/identity');+export const getChronotype = () => request('/digital-twin/identity/chronotype');+export const deriveChronotype = () => request('/digital-twin/identity/chronotype/derive', { method: 'POST' });+export const updateChronotypeBehavioral = (data) => request('/digital-twin/identity/chronotype', {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const getLongevity = () => request('/digital-twin/identity/longevity');+export const deriveLongevity = () => request('/digital-twin/identity/longevity/derive', { method: 'POST' });+export const getGoals = () => request('/digital-twin/identity/goals');+export const setBirthDate = (birthDate) => request('/digital-twin/identity/goals/birth-date', {+ method: 'PUT',+ body: JSON.stringify({ birthDate })+});+export const createGoal = (data) => request('/digital-twin/identity/goals', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateGoal = (id, data) => request(`/digital-twin/identity/goals/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteGoal = (id) => request(`/digital-twin/identity/goals/${id}`, { method: 'DELETE' });+export const addGoalMilestone = (goalId, data) => request(`/digital-twin/identity/goals/${goalId}/milestones`, {+ method: 'POST',+ body: JSON.stringify(data)+});+export const completeGoalMilestone = (goalId, milestoneId) =>+ request(`/digital-twin/identity/goals/${goalId}/milestones/${milestoneId}/complete`, { method: 'PUT' });+// JIRAexport const getJiraInstances = () => request('/jira/instances');export const getJiraProjects = (instanceId) => request(`/jira/instances/${instanceId}/projects`);diff --git a/package-lock.json b/package-lock.jsonindex 09230fe75a..6625ade0cd 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "portos",- "version": "1.7.2",+ "version": "1.7.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos",- "version": "1.7.2",+ "version": "1.7.3","license": "MIT","dependencies": {"express": "^4.21.2",diff --git a/package.json b/package.jsonindex 8a82f1b156..743dc828c3 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "1.7.2",+ "version": "1.7.3","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.jsindex 0fcb392044..fae38e00f1 100644--- a/server/lib/identityValidation.js+++ b/server/lib/identityValidation.js@@ -13,3 +13,41 @@ export const chronotypeBehavioralInputSchema = z.object({peakFocusEnd: z.string().regex(hhmmRegex, 'Must be HH:MM format').optional(),caffeineLastIntake: z.string().regex(hhmmRegex, 'Must be HH:MM format').optional()});++// --- Longevity Schemas ---++export const birthDateInputSchema = z.object({+ birthDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Must be YYYY-MM-DD format')+});++// --- Goal Schemas ---++export const goalHorizonEnum = z.enum([+ '1-year', '3-year', '5-year', '10-year', '20-year', 'lifetime'+]);++export const goalCategoryEnum = z.enum([+ 'creative', 'family', 'health', 'financial', 'legacy', 'mastery'+]);++export const goalStatusEnum = z.enum(['active', 'completed', 'abandoned']);++export const createGoalInputSchema = z.object({+ title: z.string().min(1).max(200),+ description: z.string().max(2000).optional(),+ horizon: goalHorizonEnum.optional().default('5-year'),+ category: goalCategoryEnum.optional().default('mastery')+});++export const updateGoalInputSchema = z.object({+ title: z.string().min(1).max(200).optional(),+ description: z.string().max(2000).optional(),+ horizon: goalHorizonEnum.optional(),+ category: goalCategoryEnum.optional(),+ status: goalStatusEnum.optional()+});++export const addMilestoneInputSchema = z.object({+ title: z.string().min(1).max(200),+ targetDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Must be YYYY-MM-DD format').optional()+});diff --git a/server/routes/identity.js b/server/routes/identity.jsindex 38b9c98def..04ed9958d5 100644--- a/server/routes/identity.js+++ b/server/routes/identity.js@@ -1,17 +1,31 @@import { Router } from 'express';import * as identityService from '../services/identity.js';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';-import { chronotypeBehavioralInputSchema } from '../lib/identityValidation.js';+import {+ chronotypeBehavioralInputSchema,+ birthDateInputSchema,+ createGoalInputSchema,+ updateGoalInputSchema,+ addMilestoneInputSchema+} from '../lib/identityValidation.js';const router = Router();+// =============================================================================+// IDENTITY STATUS+// =============================================================================+// GET /api/digital-twin/identity — Unified section statusrouter.get('/', asyncHandler(async (req, res) => {const status = await identityService.getIdentityStatus();res.json(status);}));+// =============================================================================+// CHRONOTYPE+// =============================================================================+// GET /api/digital-twin/identity/chronotype — Full chronotype profilerouter.get('/chronotype', asyncHandler(async (req, res) => {const chronotype = await identityService.getChronotype();@@ -31,4 +45,82 @@ router.put('/chronotype', asyncHandler(async (req, res) => {res.json(chronotype);}));+// =============================================================================+// LONGEVITY+// =============================================================================++// GET /api/digital-twin/identity/longevity — Full longevity profile+router.get('/longevity', asyncHandler(async (req, res) => {+ const longevity = await identityService.getLongevity();+ res.json(longevity);+}));++// POST /api/digital-twin/identity/longevity/derive — Force re-derivation+router.post('/longevity/derive', asyncHandler(async (req, res) => {+ const longevity = await identityService.deriveLongevity();+ res.json(longevity);+}));++// =============================================================================+// GOALS+// =============================================================================++// GET /api/digital-twin/identity/goals — Get all goals with time horizons+router.get('/goals', asyncHandler(async (req, res) => {+ const goals = await identityService.getGoals();+ res.json(goals);+}));++// PUT /api/digital-twin/identity/goals/birth-date — Set birth date+router.put('/goals/birth-date', asyncHandler(async (req, res) => {+ const { birthDate } = validateRequest(birthDateInputSchema, req.body);+ const goals = await identityService.setBirthDate(birthDate);+ res.json(goals);+}));++// POST /api/digital-twin/identity/goals — Create a new goal+router.post('/goals', asyncHandler(async (req, res) => {+ const data = validateRequest(createGoalInputSchema, req.body);+ const goal = await identityService.createGoal(data);+ res.status(201).json(goal);+}));++// PUT /api/digital-twin/identity/goals/:id — Update a goal+router.put('/goals/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(updateGoalInputSchema, req.body);+ const goal = await identityService.updateGoal(req.params.id, data);+ if (!goal) {+ throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(goal);+}));++// DELETE /api/digital-twin/identity/goals/:id — Delete a goal+router.delete('/goals/:id', asyncHandler(async (req, res) => {+ const deleted = await identityService.deleteGoal(req.params.id);+ if (!deleted) {+ throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++// POST /api/digital-twin/identity/goals/:id/milestones — Add milestone+router.post('/goals/:id/milestones', asyncHandler(async (req, res) => {+ const data = validateRequest(addMilestoneInputSchema, req.body);+ const milestone = await identityService.addMilestone(req.params.id, data);+ if (!milestone) {+ throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(201).json(milestone);+}));++// PUT /api/digital-twin/identity/goals/:id/milestones/:milestoneId/complete — Complete milestone+router.put('/goals/:id/milestones/:milestoneId/complete', asyncHandler(async (req, res) => {+ const milestone = await identityService.completeMilestone(req.params.id, req.params.milestoneId);+ if (!milestone) {+ throw new ServerError('Goal or milestone not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(milestone);+}));+export default router;diff --git a/server/services/identity.js b/server/services/identity.jsindex 16f742fe4c..e78b49e00b 100644--- a/server/services/identity.js+++ b/server/services/identity.js@@ -7,6 +7,8 @@ import { getTasteProfile } from './taste-questionnaire.js';const IDENTITY_DIR = PATHS.digitalTwin;const IDENTITY_FILE = join(IDENTITY_DIR, 'identity.json');const CHRONOTYPE_FILE = join(IDENTITY_DIR, 'chronotype.json');+const LONGEVITY_FILE = join(IDENTITY_DIR, 'longevity.json');+const GOALS_FILE = join(IDENTITY_DIR, 'goals.json');// === Marker Definitions ===@@ -68,12 +70,41 @@ const SCHEDULE_TEMPLATES = {}};+// === Longevity & Cardiovascular Marker Definitions ===++const LONGEVITY_MARKERS = {+ rs2802292: { name: 'foxo3a', gene: 'FOXO3A', weight: 0.25, label: 'Longevity / FOXO3A' },+ rs2229765: { name: 'igf1r', gene: 'IGF1R', weight: 0.20, label: 'Growth Factor Receptor' },+ rs5882: { name: 'cetp', gene: 'CETP', weight: 0.20, label: 'HDL Cholesterol' },+ rs12366: { name: 'ipmk', gene: 'IPMK', weight: 0.15, label: 'Nutrient Sensing' },+ rs10936599: { name: 'terc', gene: 'TERC', weight: 0.20, label: 'Telomere Length' }+};++const CARDIOVASCULAR_MARKERS = {+ rs6025: { name: 'factorV', gene: 'F5', weight: 0.20, label: 'Factor V Leiden' },+ rs1333049: { name: 'cad9p21', gene: '9p21.3', weight: 0.20, label: 'Coronary Artery Disease' },+ rs10455872: { name: 'lpa', gene: 'LPA', weight: 0.15, label: 'Lipoprotein(a)' },+ rs1799963: { name: 'prothrombin', gene: 'F2', weight: 0.15, label: 'Prothrombin Thrombophilia' },+ rs1800795: { name: 'il6', gene: 'IL-6', weight: 0.15, label: 'Inflammation / IL-6' },+ rs1800629: { name: 'tnfa', gene: 'TNF-alpha', weight: 0.15, label: 'Inflammation / TNF-alpha' }+};++// Longevity signal: beneficial = +1 (lifespan bonus), concern = -1 (lifespan penalty)+const LONGEVITY_SIGNAL = { beneficial: 1, typical: 0, concern: -1 };++// Cardiovascular risk: concern = +1 (adds risk), beneficial = -1 (reduces risk)+const CARDIO_SIGNAL = { beneficial: -1, typical: 0, concern: 1, major_concern: 1.5 };++// US Social Security Administration actuarial baseline by decade (average M/F)+const SSA_BASELINE_LIFE_EXPECTANCY = 78.5;+// === Default Data Structures ===const DEFAULT_IDENTITY = {sections: {genome: { status: 'unavailable', label: 'Genome', updatedAt: null },chronotype: { status: 'unavailable', label: 'Chronotype', updatedAt: null },+ longevity: { status: 'unavailable', label: 'Longevity', updatedAt: null },aesthetics: { status: 'unavailable', label: 'Aesthetics', updatedAt: null },goals: { status: 'unavailable', label: 'Goals', updatedAt: null }},@@ -90,6 +121,29 @@ const DEFAULT_CHRONOTYPE = {derivedAt: null};+const DEFAULT_LONGEVITY = {+ longevityMarkers: {},+ cardiovascularMarkers: {},+ longevityScore: 0,+ cardiovascularRisk: 0,+ lifeExpectancy: {+ baseline: SSA_BASELINE_LIFE_EXPECTANCY,+ adjusted: null,+ longevityAdjustment: 0,+ cardiovascularAdjustment: 0+ },+ confidence: 0,+ derivedAt: null+};++const DEFAULT_GOALS = {+ birthDate: null,+ lifeExpectancy: null,+ timeHorizons: null,+ goals: [],+ updatedAt: null+};+// === File I/O ===async function ensureIdentityDir() {@@ -148,6 +202,145 @@ export function extractCaffeineMarkers(savedMarkers) {return results;}+export function extractLongevityMarkers(savedMarkers) {+ const results = {};+ const markerValues = Object.values(savedMarkers || {});++ for (const [rsid, def] of Object.entries(LONGEVITY_MARKERS)) {+ const found = markerValues.find(m => m.rsid === rsid);+ if (found) {+ const signal = LONGEVITY_SIGNAL[found.status] ?? 0;+ results[def.name] = {+ rsid,+ gene: def.gene,+ label: def.label,+ genotype: found.genotype,+ status: found.status,+ weight: def.weight,+ signal+ };+ }+ }++ return results;+}++export function extractCardiovascularMarkers(savedMarkers) {+ const results = {};+ const markerValues = Object.values(savedMarkers || {});++ for (const [rsid, def] of Object.entries(CARDIOVASCULAR_MARKERS)) {+ const found = markerValues.find(m => m.rsid === rsid);+ if (found) {+ const signal = CARDIO_SIGNAL[found.status] ?? 0;+ results[def.name] = {+ rsid,+ gene: def.gene,+ label: def.label,+ genotype: found.genotype,+ status: found.status,+ weight: def.weight,+ signal+ };+ }+ }++ return results;+}++export function computeLifeExpectancy(longevityMarkers, cardiovascularMarkers, birthDate) {+ // Longevity score: weighted average of signals (+1 beneficial, -1 concern)+ let longevityScore = 0;+ let longevityWeight = 0;+ for (const marker of Object.values(longevityMarkers)) {+ longevityScore += marker.signal * marker.weight;+ longevityWeight += marker.weight;+ }+ if (longevityWeight > 0) longevityScore /= longevityWeight;++ // Cardiovascular risk: weighted average of signals (+1 concern adds risk)+ let cardioRisk = 0;+ let cardioWeight = 0;+ for (const marker of Object.values(cardiovascularMarkers)) {+ cardioRisk += marker.signal * marker.weight;+ cardioWeight += marker.weight;+ }+ if (cardioWeight > 0) cardioRisk /= cardioWeight;++ // Longevity adjustment: max ±5 years from favorable/unfavorable longevity markers+ const longevityAdjustment = Math.round(longevityScore * 5 * 100) / 100 || 0;++ // Cardiovascular adjustment: max ±4 years from cardio risk markers+ const cardiovascularAdjustment = Math.round(-cardioRisk * 4 * 100) / 100 || 0;++ const adjusted = Math.round((SSA_BASELINE_LIFE_EXPECTANCY + longevityAdjustment + cardiovascularAdjustment) * 10) / 10;++ // Confidence based on marker coverage+ const longevityCount = Object.keys(longevityMarkers).length;+ const cardioCount = Object.keys(cardiovascularMarkers).length;+ const maxLongevity = Object.keys(LONGEVITY_MARKERS).length;+ const maxCardio = Object.keys(CARDIOVASCULAR_MARKERS).length;+ const coverage = (longevityCount + cardioCount) / (maxLongevity + maxCardio);+ const confidence = Math.round(Math.min(1, coverage) * 100) / 100;++ // Time horizons if birth date provided+ let timeHorizons = null;+ if (birthDate) {+ const birth = new Date(birthDate);+ const now = new Date();+ const ageYears = (now - birth) / (365.25 * 24 * 60 * 60 * 1000);+ const yearsRemaining = Math.max(0, Math.round((adjusted - ageYears) * 10) / 10);+ // Healthy years: estimate ~85% of remaining years are active/healthy+ const healthyYearsRemaining = Math.round(yearsRemaining * 0.85 * 10) / 10;+ const percentLifeComplete = Math.round((ageYears / adjusted) * 1000) / 10;++ timeHorizons = {+ ageYears: Math.round(ageYears * 10) / 10,+ yearsRemaining,+ healthyYearsRemaining,+ percentLifeComplete: Math.min(100, percentLifeComplete)+ };+ }++ return {+ longevityScore: Math.round(longevityScore * 1000) / 1000,+ cardiovascularRisk: Math.round(cardioRisk * 1000) / 1000,+ lifeExpectancy: {+ baseline: SSA_BASELINE_LIFE_EXPECTANCY,+ adjusted,+ longevityAdjustment,+ cardiovascularAdjustment+ },+ timeHorizons,+ confidence+ };+}++export function computeGoalUrgency(goal, timeHorizons) {+ if (!timeHorizons || !goal.horizon) return null;++ const horizonMap = {+ '1-year': 1,+ '3-year': 3,+ '5-year': 5,+ '10-year': 10,+ '20-year': 20,+ 'lifetime': timeHorizons.yearsRemaining+ };++ const horizonYears = horizonMap[goal.horizon] ?? 5;+ const yearsRemaining = timeHorizons.yearsRemaining;++ // Urgency: higher when horizon approaches or exceeds remaining years+ // 0 = plenty of time, 1 = urgent+ const rawUrgency = 1 - Math.min(1, yearsRemaining / (horizonYears * 2));+ // Boost urgency for goals whose horizon exceeds remaining healthy years+ const healthPressure = horizonYears > timeHorizons.healthyYearsRemaining ? 0.2 : 0;+ const urgency = Math.min(1, Math.round((rawUrgency + healthPressure) * 100) / 100);++ return urgency;+}+export function computeChronotype(geneticMarkers, behavioralData) {const markerNames = Object.keys(geneticMarkers);const hasGenetic = markerNames.length > 0;@@ -302,6 +495,27 @@ export async function getIdentityStatus() {};}+ // Check longevity status+ const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);+ if (longevity.derivedAt) {+ const markerCount = Object.keys(longevity.longevityMarkers).length ++ Object.keys(longevity.cardiovascularMarkers).length;+ identity.sections.longevity = {+ status: 'active',+ label: 'Longevity',+ markerCount,+ adjustedLifeExpectancy: longevity.lifeExpectancy?.adjusted,+ confidence: longevity.confidence,+ updatedAt: longevity.derivedAt+ };+ } else {+ identity.sections.longevity = {+ status: genomeSummary?.uploaded ? 'pending' : 'unavailable',+ label: 'Longevity',+ updatedAt: null+ };+ }+// Check aesthetics (taste profile) statusconst tasteProfile = await getTasteProfile();if (tasteProfile?.completedCount > 0) {@@ -316,14 +530,27 @@ export async function getIdentityStatus() {identity.sections.aesthetics = { status: 'unavailable', label: 'Aesthetics', updatedAt: null };}- // Goals status — check if GOALS.md exists- const goalsPath = join(PATHS.root, 'GOALS.md');- const goalsExist = await readFile(goalsPath, 'utf-8').catch(() => null);- identity.sections.goals = {- status: goalsExist ? 'active' : 'unavailable',- label: 'Goals',- updatedAt: goalsExist ? new Date().toISOString() : null- };+ // Goals status — check goals.json for user-defined goals+ const goalsData = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const activeGoals = goalsData.goals?.filter(g => g.status === 'active') || [];+ if (activeGoals.length > 0) {+ identity.sections.goals = {+ status: 'active',+ label: 'Goals',+ goalCount: activeGoals.length,+ hasBirthDate: !!goalsData.birthDate,+ updatedAt: goalsData.updatedAt+ };+ } else if (goalsData.birthDate) {+ identity.sections.goals = {+ status: 'pending',+ label: 'Goals',+ hasBirthDate: true,+ updatedAt: goalsData.updatedAt+ };+ } else {+ identity.sections.goals = { status: 'unavailable', label: 'Goals', updatedAt: null };+ }identity.updatedAt = new Date().toISOString();await saveJSON(IDENTITY_FILE, identity);@@ -380,3 +607,173 @@ export async function updateChronotypeBehavioral(overrides) {return deriveChronotype();}++// === Longevity Service Functions ===++export async function getLongevity() {+ const existing = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);+ if (existing.derivedAt) return existing;+ return deriveLongevity();+}++export async function deriveLongevity(birthDate) {+ const genomeSummary = await getGenomeSummary();+ const savedMarkers = genomeSummary?.savedMarkers || {};++ const longevityMarkers = extractLongevityMarkers(savedMarkers);+ const cardiovascularMarkers = extractCardiovascularMarkers(savedMarkers);++ // Use provided birthDate or fall back to stored goals birthDate+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const effectiveBirthDate = birthDate || goals.birthDate || null;++ const { longevityScore, cardiovascularRisk, lifeExpectancy, timeHorizons, confidence } =+ computeLifeExpectancy(longevityMarkers, cardiovascularMarkers, effectiveBirthDate);++ const longevity = {+ longevityMarkers,+ cardiovascularMarkers,+ longevityScore,+ cardiovascularRisk,+ lifeExpectancy,+ timeHorizons,+ confidence,+ derivedAt: new Date().toISOString()+ };++ await saveJSON(LONGEVITY_FILE, longevity);+ const markerCount = Object.keys(longevityMarkers).length + Object.keys(cardiovascularMarkers).length;+ console.log(`🧬 Longevity derived: ${lifeExpectancy.adjusted}y (${markerCount} markers, confidence: ${confidence})`);++ return longevity;+}++// === Goal Service Functions ===++export async function getGoals() {+ return loadJSON(GOALS_FILE, DEFAULT_GOALS);+}++export async function setBirthDate(birthDate) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ goals.birthDate = birthDate;+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);++ // Re-derive longevity with new birth date+ const longevity = await deriveLongevity(birthDate);++ // Recalculate urgency for all active goals+ if (longevity.timeHorizons) {+ for (const goal of goals.goals) {+ if (goal.status === 'active') {+ goal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);+ }+ }+ goals.lifeExpectancy = longevity.lifeExpectancy;+ goals.timeHorizons = longevity.timeHorizons;+ await saveJSON(GOALS_FILE, goals);+ }++ return goals;+}++export async function createGoal({ title, description, horizon, category }) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);++ const id = `goal-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+ const goal = {+ id,+ title,+ description: description || '',+ horizon: horizon || '5-year',+ category: category || 'mastery',+ urgency: null,+ status: 'active',+ milestones: [],+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString()+ };++ // Calculate urgency if time horizons available+ if (longevity.timeHorizons) {+ goal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);+ }++ goals.goals.push(goal);+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);++ console.log(`🎯 Goal created: "${title}" (${horizon}, urgency: ${goal.urgency ?? 'n/a'})`);+ return goal;+}++export async function updateGoal(goalId, updates) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const idx = goals.goals.findIndex(g => g.id === goalId);+ if (idx === -1) return null;++ const goal = goals.goals[idx];+ const allowed = ['title', 'description', 'horizon', 'category', 'status'];+ for (const key of allowed) {+ if (updates[key] !== undefined) goal[key] = updates[key];+ }+ goal.updatedAt = new Date().toISOString();++ // Recalculate urgency if horizon changed+ const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);+ if (longevity.timeHorizons) {+ goal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);+ }++ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ return goal;+}++export async function deleteGoal(goalId) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const idx = goals.goals.findIndex(g => g.id === goalId);+ if (idx === -1) return false;++ goals.goals.splice(idx, 1);+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ return true;+}++export async function addMilestone(goalId, { title, targetDate }) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ const milestone = {+ id: `ms-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,+ title,+ targetDate: targetDate || null,+ completedAt: null,+ createdAt: new Date().toISOString()+ };++ goal.milestones.push(milestone);+ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ return milestone;+}++export async function completeMilestone(goalId, milestoneId) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ const milestone = goal.milestones.find(m => m.id === milestoneId);+ if (!milestone) return null;++ milestone.completedAt = new Date().toISOString();+ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ return milestone;+}diff --git a/server/services/identity.test.js b/server/services/identity.test.jsindex 5a933c4cf6..7cfd994e4a 100644--- a/server/services/identity.test.js+++ b/server/services/identity.test.js@@ -497,6 +497,348 @@ describe('computeRecommendations', () => {});});+// === Longevity & Goal pure function copies ===++const LONGEVITY_MARKERS = {+ rs2802292: { name: 'foxo3a', gene: 'FOXO3A', weight: 0.25, label: 'Longevity / FOXO3A' },+ rs2229765: { name: 'igf1r', gene: 'IGF1R', weight: 0.20, label: 'Growth Factor Receptor' },+ rs5882: { name: 'cetp', gene: 'CETP', weight: 0.20, label: 'HDL Cholesterol' },+ rs12366: { name: 'ipmk', gene: 'IPMK', weight: 0.15, label: 'Nutrient Sensing' },+ rs10936599: { name: 'terc', gene: 'TERC', weight: 0.20, label: 'Telomere Length' }+};++const CARDIOVASCULAR_MARKERS = {+ rs6025: { name: 'factorV', gene: 'F5', weight: 0.20, label: 'Factor V Leiden' },+ rs1333049: { name: 'cad9p21', gene: '9p21.3', weight: 0.20, label: 'Coronary Artery Disease' },+ rs10455872: { name: 'lpa', gene: 'LPA', weight: 0.15, label: 'Lipoprotein(a)' },+ rs1799963: { name: 'prothrombin', gene: 'F2', weight: 0.15, label: 'Prothrombin Thrombophilia' },+ rs1800795: { name: 'il6', gene: 'IL-6', weight: 0.15, label: 'Inflammation / IL-6' },+ rs1800629: { name: 'tnfa', gene: 'TNF-alpha', weight: 0.15, label: 'Inflammation / TNF-alpha' }+};++const LONGEVITY_SIGNAL = { beneficial: 1, typical: 0, concern: -1 };+const CARDIO_SIGNAL = { beneficial: -1, typical: 0, concern: 1, major_concern: 1.5 };+const SSA_BASELINE_LIFE_EXPECTANCY = 78.5;++function extractLongevityMarkers(savedMarkers) {+ const results = {};+ const markerValues = Object.values(savedMarkers || {});+ for (const [rsid, def] of Object.entries(LONGEVITY_MARKERS)) {+ const found = markerValues.find(m => m.rsid === rsid);+ if (found) {+ const signal = LONGEVITY_SIGNAL[found.status] ?? 0;+ results[def.name] = {+ rsid, gene: def.gene, label: def.label,+ genotype: found.genotype, status: found.status,+ weight: def.weight, signal+ };+ }+ }+ return results;+}++function extractCardiovascularMarkers(savedMarkers) {+ const results = {};+ const markerValues = Object.values(savedMarkers || {});+ for (const [rsid, def] of Object.entries(CARDIOVASCULAR_MARKERS)) {+ const found = markerValues.find(m => m.rsid === rsid);+ if (found) {+ const signal = CARDIO_SIGNAL[found.status] ?? 0;+ results[def.name] = {+ rsid, gene: def.gene, label: def.label,+ genotype: found.genotype, status: found.status,+ weight: def.weight, signal+ };+ }+ }+ return results;+}++function computeLifeExpectancy(longevityMarkers, cardiovascularMarkers, birthDate) {+ let longevityScore = 0;+ let longevityWeight = 0;+ for (const marker of Object.values(longevityMarkers)) {+ longevityScore += marker.signal * marker.weight;+ longevityWeight += marker.weight;+ }+ if (longevityWeight > 0) longevityScore /= longevityWeight;++ let cardioRisk = 0;+ let cardioWeight = 0;+ for (const marker of Object.values(cardiovascularMarkers)) {+ cardioRisk += marker.signal * marker.weight;+ cardioWeight += marker.weight;+ }+ if (cardioWeight > 0) cardioRisk /= cardioWeight;++ const longevityAdjustment = Math.round(longevityScore * 5 * 100) / 100 || 0;+ const cardiovascularAdjustment = Math.round(-cardioRisk * 4 * 100) / 100 || 0;+ const adjusted = Math.round((SSA_BASELINE_LIFE_EXPECTANCY + longevityAdjustment + cardiovascularAdjustment) * 10) / 10;++ const longevityCount = Object.keys(longevityMarkers).length;+ const cardioCount = Object.keys(cardiovascularMarkers).length;+ const maxLongevity = Object.keys(LONGEVITY_MARKERS).length;+ const maxCardio = Object.keys(CARDIOVASCULAR_MARKERS).length;+ const coverage = (longevityCount + cardioCount) / (maxLongevity + maxCardio);+ const confidence = Math.round(Math.min(1, coverage) * 100) / 100;++ let timeHorizons = null;+ if (birthDate) {+ const birth = new Date(birthDate);+ const now = new Date();+ const ageYears = (now - birth) / (365.25 * 24 * 60 * 60 * 1000);+ const yearsRemaining = Math.max(0, Math.round((adjusted - ageYears) * 10) / 10);+ const healthyYearsRemaining = Math.round(yearsRemaining * 0.85 * 10) / 10;+ const percentLifeComplete = Math.round((ageYears / adjusted) * 1000) / 10;++ timeHorizons = {+ ageYears: Math.round(ageYears * 10) / 10,+ yearsRemaining,+ healthyYearsRemaining,+ percentLifeComplete: Math.min(100, percentLifeComplete)+ };+ }++ return {+ longevityScore: Math.round(longevityScore * 1000) / 1000,+ cardiovascularRisk: Math.round(cardioRisk * 1000) / 1000,+ lifeExpectancy: {+ baseline: SSA_BASELINE_LIFE_EXPECTANCY,+ adjusted,+ longevityAdjustment,+ cardiovascularAdjustment+ },+ timeHorizons,+ confidence+ };+}++function computeGoalUrgency(goal, timeHorizons) {+ if (!timeHorizons || !goal.horizon) return null;+ const horizonMap = {+ '1-year': 1, '3-year': 3, '5-year': 5,+ '10-year': 10, '20-year': 20, 'lifetime': timeHorizons.yearsRemaining+ };+ const horizonYears = horizonMap[goal.horizon] ?? 5;+ const yearsRemaining = timeHorizons.yearsRemaining;+ const rawUrgency = 1 - Math.min(1, yearsRemaining / (horizonYears * 2));+ const healthPressure = horizonYears > timeHorizons.healthyYearsRemaining ? 0.2 : 0;+ return Math.min(1, Math.round((rawUrgency + healthPressure) * 100) / 100);+}++// ============================================================+// Longevity Tests+// ============================================================++describe('extractLongevityMarkers', () => {+ it('should extract all 5 longevity markers when present', () => {+ const saved = buildSavedMarkers([+ ['rs2802292', 'beneficial', 'TG'],+ ['rs2229765', 'typical', 'GG'],+ ['rs5882', 'concern', 'AG'],+ ['rs12366', 'beneficial', 'AA'],+ ['rs10936599', 'typical', 'TT']+ ]);++ const result = extractLongevityMarkers(saved);++ expect(Object.keys(result)).toHaveLength(5);+ expect(result.foxo3a.rsid).toBe('rs2802292');+ expect(result.foxo3a.signal).toBe(1); // beneficial = +1 longevity+ expect(result.cetp.signal).toBe(-1); // concern = -1 longevity+ expect(result.igf1r.signal).toBe(0); // typical = neutral+ });++ it('should return partial results for missing markers', () => {+ const saved = buildSavedMarkers([+ ['rs2802292', 'beneficial', 'TG']+ ]);++ const result = extractLongevityMarkers(saved);+ expect(Object.keys(result)).toHaveLength(1);+ expect(result.foxo3a).toBeDefined();+ expect(result.igf1r).toBeUndefined();+ });++ it('should return empty for no longevity markers', () => {+ expect(extractLongevityMarkers({})).toEqual({});+ expect(extractLongevityMarkers(null)).toEqual({});+ });++ it('should ignore non-longevity markers', () => {+ const saved = buildSavedMarkers([+ ['rs1801260', 'beneficial', 'AA'] // sleep marker+ ]);+ expect(extractLongevityMarkers(saved)).toEqual({});+ });+});++describe('extractCardiovascularMarkers', () => {+ it('should extract all 6 cardiovascular markers when present', () => {+ const saved = buildSavedMarkers([+ ['rs6025', 'typical', 'GG'],+ ['rs1333049', 'concern', 'CC'],+ ['rs10455872', 'beneficial', 'AA'],+ ['rs1799963', 'typical', 'GG'],+ ['rs1800795', 'concern', 'CC'],+ ['rs1800629', 'typical', 'GG']+ ]);++ const result = extractCardiovascularMarkers(saved);++ expect(Object.keys(result)).toHaveLength(6);+ expect(result.cad9p21.signal).toBe(1); // concern = +1 risk+ expect(result.lpa.signal).toBe(-1); // beneficial = -1 risk+ expect(result.factorV.signal).toBe(0); // typical = neutral+ });++ it('should handle major_concern status', () => {+ const saved = buildSavedMarkers([+ ['rs6025', 'major_concern', 'AA']+ ]);++ const result = extractCardiovascularMarkers(saved);+ expect(result.factorV.signal).toBe(1.5); // major_concern = 1.5 risk+ });++ it('should return empty for no cardiovascular markers', () => {+ expect(extractCardiovascularMarkers({})).toEqual({});+ });+});++describe('computeLifeExpectancy', () => {+ it('should return baseline when no markers present', () => {+ const result = computeLifeExpectancy({}, {}, null);++ expect(result.lifeExpectancy.baseline).toBe(78.5);+ expect(result.lifeExpectancy.adjusted).toBe(78.5);+ expect(result.lifeExpectancy.longevityAdjustment).toBe(0);+ expect(result.lifeExpectancy.cardiovascularAdjustment).toBe(0);+ expect(result.confidence).toBe(0);+ expect(result.timeHorizons).toBeNull();+ });++ it('should increase life expectancy for beneficial longevity markers', () => {+ const longevity = {+ foxo3a: { signal: 1, weight: 0.25 },+ igf1r: { signal: 1, weight: 0.20 },+ cetp: { signal: 1, weight: 0.20 }+ };++ const result = computeLifeExpectancy(longevity, {}, null);++ expect(result.lifeExpectancy.adjusted).toBeGreaterThan(78.5);+ expect(result.lifeExpectancy.longevityAdjustment).toBeGreaterThan(0);+ expect(result.longevityScore).toBe(1); // all beneficial+ });++ it('should decrease life expectancy for cardiovascular risk markers', () => {+ const cardio = {+ factorV: { signal: 1, weight: 0.20 },+ cad9p21: { signal: 1, weight: 0.20 },+ il6: { signal: 1, weight: 0.15 }+ };++ const result = computeLifeExpectancy({}, cardio, null);++ expect(result.lifeExpectancy.adjusted).toBeLessThan(78.5);+ expect(result.lifeExpectancy.cardiovascularAdjustment).toBeLessThan(0);+ expect(result.cardiovascularRisk).toBe(1); // all concern+ });++ it('should balance longevity and cardiovascular adjustments', () => {+ const longevity = { foxo3a: { signal: 1, weight: 0.25 } };+ const cardio = { factorV: { signal: 1, weight: 0.20 } };++ const result = computeLifeExpectancy(longevity, cardio, null);++ // Longevity adds years, cardio subtracts — result depends on relative magnitude+ expect(result.lifeExpectancy.longevityAdjustment).toBeGreaterThan(0);+ expect(result.lifeExpectancy.cardiovascularAdjustment).toBeLessThan(0);+ });++ it('should calculate time horizons when birth date provided', () => {+ const result = computeLifeExpectancy({}, {}, '1980-01-15');++ expect(result.timeHorizons).not.toBeNull();+ expect(result.timeHorizons.ageYears).toBeGreaterThan(40);+ expect(result.timeHorizons.yearsRemaining).toBeGreaterThan(0);+ expect(result.timeHorizons.healthyYearsRemaining).toBeLessThan(result.timeHorizons.yearsRemaining);+ expect(result.timeHorizons.percentLifeComplete).toBeGreaterThan(0);+ expect(result.timeHorizons.percentLifeComplete).toBeLessThan(100);+ });++ it('should not exceed 100% life complete', () => {+ // Very old birth date+ const result = computeLifeExpectancy({}, {}, '1920-01-01');++ expect(result.timeHorizons.percentLifeComplete).toBe(100);+ expect(result.timeHorizons.yearsRemaining).toBe(0);+ });++ it('should calculate confidence based on marker coverage', () => {+ const longevity = {+ foxo3a: { signal: 0, weight: 0.25 },+ igf1r: { signal: 0, weight: 0.20 }+ };+ const cardio = {+ factorV: { signal: 0, weight: 0.20 }+ };++ const result = computeLifeExpectancy(longevity, cardio, null);++ // 3 out of 11 total markers = ~0.27+ expect(result.confidence).toBeGreaterThan(0.2);+ expect(result.confidence).toBeLessThan(0.4);+ });+});++describe('computeGoalUrgency', () => {+ const baseHorizons = {+ ageYears: 45,+ yearsRemaining: 33.5,+ healthyYearsRemaining: 28.5,+ percentLifeComplete: 57.3+ };++ it('should return null when no time horizons', () => {+ expect(computeGoalUrgency({ horizon: '5-year' }, null)).toBeNull();+ });++ it('should return null when goal has no horizon', () => {+ expect(computeGoalUrgency({}, baseHorizons)).toBeNull();+ });++ it('should return low urgency for short-horizon goals with plenty of time', () => {+ const urgency = computeGoalUrgency({ horizon: '1-year' }, baseHorizons);+ expect(urgency).toBeLessThan(0.1);+ });++ it('should return higher urgency for lifetime goals', () => {+ const lifetime = computeGoalUrgency({ horizon: 'lifetime' }, baseHorizons);+ const shortTerm = computeGoalUrgency({ horizon: '1-year' }, baseHorizons);+ expect(lifetime).toBeGreaterThan(shortTerm);+ });++ it('should add health pressure for goals exceeding healthy years', () => {+ const horizons = { ...baseHorizons, healthyYearsRemaining: 3 };+ const urgency = computeGoalUrgency({ horizon: '5-year' }, horizons);+ // 5-year > 3 healthy years → health pressure adds 0.2+ expect(urgency).toBeGreaterThan(0);+ });++ it('should cap urgency at 1.0', () => {+ const tightHorizons = {+ ageYears: 75,+ yearsRemaining: 3,+ healthyYearsRemaining: 1,+ percentLifeComplete: 96+ };+ const urgency = computeGoalUrgency({ horizon: '20-year' }, tightHorizons);+ expect(urgency).toBeLessThanOrEqual(1);+ });+});+// === Integration tests (mock fs + genome service) ===describe('Integration: deriveChronotype', () => {@@ -643,11 +985,12 @@ describe('Integration: getIdentityStatus', () => {getIdentityStatus = mod.getIdentityStatus;});- it('should return all four sections', async () => {+ it('should return all five sections', async () => {const result = await getIdentityStatus();expect(result.sections.genome).toBeDefined();expect(result.sections.chronotype).toBeDefined();+ expect(result.sections.longevity).toBeDefined();expect(result.sections.aesthetics).toBeDefined();expect(result.sections.goals).toBeDefined();});@@ -699,4 +1042,250 @@ describe('Integration: getIdentityStatus', () => {expect(result.sections.chronotype.status).toBe('pending');});++ it('should show longevity as pending when genome uploaded but not derived', async () => {+ const result = await getIdentityStatus();++ expect(result.sections.longevity.status).toBe('pending');+ });++ it('should show goals as unavailable when no birth date or goals', async () => {+ const result = await getIdentityStatus();++ expect(result.sections.goals.status).toBe('unavailable');+ });+});++describe('Integration: deriveLongevity', () => {+ let deriveLongevity, getLongevity;++ beforeEach(async () => {+ vi.resetModules();++ vi.doMock('fs/promises', () => {+ const store = {};+ return {+ readFile: vi.fn(async (path) => {+ if (store[path]) return store[path];+ throw new Error('ENOENT');+ }),+ writeFile: vi.fn(async (path, data) => {+ store[path] = data;+ }),+ mkdir: vi.fn(async () => {})+ };+ });++ vi.doMock('./genome.js', () => ({+ getGenomeSummary: vi.fn(async () => ({+ uploaded: true,+ markerCount: 13,+ uploadedAt: '2025-01-01T00:00:00.000Z',+ savedMarkers: buildSavedMarkers([+ // Longevity markers+ ['rs2802292', 'beneficial', 'TG'], // FOXO3A — beneficial+ ['rs2229765', 'typical', 'GG'], // IGF1R — neutral+ ['rs5882', 'beneficial', 'AA'], // CETP — beneficial+ ['rs12366', 'typical', 'AG'], // IPMK — neutral+ ['rs10936599', 'concern', 'TT'], // TERC — concern+ // Cardiovascular markers+ ['rs6025', 'typical', 'GG'], // Factor V — neutral+ ['rs1333049', 'concern', 'CC'], // CAD 9p21 — concern+ ['rs10455872', 'typical', 'GG'], // LPA — neutral+ ['rs1799963', 'typical', 'GG'], // Prothrombin — neutral+ ['rs1800795', 'concern', 'CC'], // IL-6 — concern+ ['rs1800629', 'typical', 'GG'] // TNF-alpha — neutral+ ])+ }))+ }));++ vi.doMock('./taste-questionnaire.js', () => ({+ getTasteProfile: vi.fn(async () => ({+ completedCount: 0, totalSections: 5, overallPercentage: 0, lastSessionAt: null+ }))+ }));++ const mod = await import('./identity.js');+ deriveLongevity = mod.deriveLongevity;+ getLongevity = mod.getLongevity;+ });++ it('should derive longevity from genome markers', async () => {+ const result = await deriveLongevity();++ expect(result.derivedAt).toBeDefined();+ expect(Object.keys(result.longevityMarkers)).toHaveLength(5);+ expect(Object.keys(result.cardiovascularMarkers)).toHaveLength(6);+ expect(result.lifeExpectancy.baseline).toBe(78.5);+ expect(result.lifeExpectancy.adjusted).toBeDefined();+ expect(result.confidence).toBeGreaterThan(0.9); // 11/11 markers+ });++ it('should calculate positive longevity adjustment for beneficial markers', async () => {+ const result = await deriveLongevity();++ // 2 beneficial, 2 typical, 1 concern → net positive longevity+ expect(result.longevityScore).toBeGreaterThan(-0.5);+ });++ it('should include time horizons when birth date provided', async () => {+ const result = await deriveLongevity('1980-06-15');++ expect(result.timeHorizons).not.toBeNull();+ expect(result.timeHorizons.ageYears).toBeGreaterThan(40);+ expect(result.timeHorizons.yearsRemaining).toBeGreaterThan(0);+ });++ it('should return cached longevity on second getLongevity call', async () => {+ const first = await getLongevity();+ const second = await getLongevity();++ expect(first.derivedAt).toBe(second.derivedAt);+ });+});++describe('Integration: Goal CRUD', () => {+ let createGoal, getGoals, updateGoal, deleteGoal, setBirthDate, addMilestone, completeMilestone;++ beforeEach(async () => {+ vi.resetModules();++ vi.doMock('fs/promises', () => {+ const store = {};+ return {+ readFile: vi.fn(async (path) => {+ if (store[path]) return store[path];+ throw new Error('ENOENT');+ }),+ writeFile: vi.fn(async (path, data) => {+ store[path] = data;+ }),+ mkdir: vi.fn(async () => {})+ };+ });++ vi.doMock('./genome.js', () => ({+ getGenomeSummary: vi.fn(async () => ({+ uploaded: true,+ markerCount: 0,+ uploadedAt: '2025-01-01T00:00:00.000Z',+ savedMarkers: {}+ }))+ }));++ vi.doMock('./taste-questionnaire.js', () => ({+ getTasteProfile: vi.fn(async () => ({+ completedCount: 0, totalSections: 5, overallPercentage: 0, lastSessionAt: null+ }))+ }));++ const mod = await import('./identity.js');+ createGoal = mod.createGoal;+ getGoals = mod.getGoals;+ updateGoal = mod.updateGoal;+ deleteGoal = mod.deleteGoal;+ setBirthDate = mod.setBirthDate;+ addMilestone = mod.addMilestone;+ completeMilestone = mod.completeMilestone;+ });++ it('should create a goal with defaults', async () => {+ const goal = await createGoal({ title: 'Learn piano' });++ expect(goal.id).toBeDefined();+ expect(goal.title).toBe('Learn piano');+ expect(goal.horizon).toBe('5-year');+ expect(goal.category).toBe('mastery');+ expect(goal.status).toBe('active');+ expect(goal.milestones).toEqual([]);+ expect(goal.createdAt).toBeDefined();+ });++ it('should create a goal with custom fields', async () => {+ const goal = await createGoal({+ title: 'Run a marathon',+ description: 'Complete a full 26.2 mile marathon',+ horizon: '3-year',+ category: 'health'+ });++ expect(goal.title).toBe('Run a marathon');+ expect(goal.description).toBe('Complete a full 26.2 mile marathon');+ expect(goal.horizon).toBe('3-year');+ expect(goal.category).toBe('health');+ });++ it('should persist goals across reads', async () => {+ await createGoal({ title: 'Goal 1' });+ await createGoal({ title: 'Goal 2' });++ const goals = await getGoals();+ expect(goals.goals).toHaveLength(2);+ expect(goals.goals[0].title).toBe('Goal 1');+ expect(goals.goals[1].title).toBe('Goal 2');+ });++ it('should update a goal', async () => {+ const goal = await createGoal({ title: 'Original' });+ const updated = await updateGoal(goal.id, { title: 'Updated', status: 'completed' });++ expect(updated.title).toBe('Updated');+ expect(updated.status).toBe('completed');+ });++ it('should return null for updating non-existent goal', async () => {+ const result = await updateGoal('nonexistent', { title: 'Nope' });+ expect(result).toBeNull();+ });++ it('should delete a goal', async () => {+ const goal = await createGoal({ title: 'To Delete' });+ expect(await deleteGoal(goal.id)).toBe(true);++ const goals = await getGoals();+ expect(goals.goals).toHaveLength(0);+ });++ it('should return false for deleting non-existent goal', async () => {+ expect(await deleteGoal('nonexistent')).toBe(false);+ });++ it('should set birth date and re-derive longevity', async () => {+ const goals = await setBirthDate('1985-03-20');++ expect(goals.birthDate).toBe('1985-03-20');+ expect(goals.updatedAt).toBeDefined();+ });++ it('should add milestone to a goal', async () => {+ const goal = await createGoal({ title: 'With milestones' });+ const milestone = await addMilestone(goal.id, {+ title: 'First milestone',+ targetDate: '2026-06-01'+ });++ expect(milestone.id).toBeDefined();+ expect(milestone.title).toBe('First milestone');+ expect(milestone.targetDate).toBe('2026-06-01');+ expect(milestone.completedAt).toBeNull();+ });++ it('should return null when adding milestone to non-existent goal', async () => {+ const result = await addMilestone('nonexistent', { title: 'Nope' });+ expect(result).toBeNull();+ });++ it('should complete a milestone', async () => {+ const goal = await createGoal({ title: 'With milestones' });+ const milestone = await addMilestone(goal.id, { title: 'Complete me' });+ const completed = await completeMilestone(goal.id, milestone.id);++ expect(completed.completedAt).toBeDefined();+ });++ it('should return null for completing non-existent milestone', async () => {+ const goal = await createGoal({ title: 'Test' });+ expect(await completeMilestone(goal.id, 'nonexistent')).toBeNull();+ expect(await completeMilestone('nonexistent', 'fake')).toBeNull();+ });});