Skip to content

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

feat(digital-twin): add cognitive decline genetic panel and epigenetic lifestyle tracking

Adam Eivy58678960fd2d
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.md
index ee7b8fc404..39feafbb5a 100644
--- a/.changelog/v0.12.x.md
+++ b/.changelog/v0.12.x.md
@@ -625,6 +625,38 @@ This release adds branch management and automated release workflow capabilities
- **Fix**: 9 prompt templates (`soul-contradiction-detector`, `soul-enrichment`, `soul-enrichment-process`, `soul-test-generator`, `soul-test-scorer`, `soul-writing-analyzer`, `twin-trait-extractor`, `twin-confidence-analyzer`, `twin-import-analyzer`) had `.md` template files in `data/prompts/stages/` but were missing entries in `stage-config.json`. The toolkit's `buildPrompt()` requires both a config entry and a template file — without the config entry, all calls returned "not found" errors.
- **Solution**: Added all 9 missing stage entries to both `data/prompts/stage-config.json` and `data.sample/prompts/stage-config.json`
+### Digital Twin — Cognitive Decline & Dementia Risk Genetic Panel
+- **11 new SNP markers** in a dedicated "Cognitive Decline & Dementia Risk" category covering the most well-replicated Alzheimer's disease risk loci
+ - **APOE ε4 (rs429358)**: The strongest common genetic risk factor — 3x risk per allele, 12x for homozygous
+ - **APOE ε2 (rs7412)**: Protective counterpart — 40% reduced risk for carriers
+ - **BIN1 (rs744373)**: Second strongest AD risk locus after APOE — tau pathology and synaptic function
+ - **CD33 (rs3865444)**: Microglial amyloid clearance efficiency
+ - **ABCA7 (rs3764650)**: Lipid transport and amyloid processing (1.8x risk)
+ - **CR1 (rs6656401)**: Complement receptor 1 — neuroinflammation
+ - **CLU (rs11136000)**: Clusterin/apolipoprotein J — amyloid clearance across BBB
+ - **PICALM (rs9349407, rs3851179)**: Endocytic clearance and autophagy/tau clearance
+ - **CD2AP (rs10948363)**: Blood-brain barrier integrity
+ - **MS4A6A (rs983392)**: Microglial activation and TREM2 levels
+- **Category card**: Rose-colored category with elderly person emoji, sorted after cardiovascular and tumor suppression
+
+### Digital Twin — Epigenetic Lifestyle Tracking & Neuroprotective Recommendations
+- **Curated intervention database**: 12 evidence-based neuroprotective interventions with mechanisms, dosage ranges, evidence levels, and research references — creatine, omega-3 DHA, aerobic exercise, sleep optimization, vitamin D, meditation, B-vitamins, curcumin, cognitive training, social engagement, magnesium L-threonate, and lion's mane
+- **Personalized recommendations**: Interventions are filtered by the user's detected genetic marker categories — if you have cognitive_decline markers scanned, you'll see interventions targeting those pathways
+- **Daily logging**: Track intake/activity amounts with per-intervention log entries, deduplication by date, and sorted log history
+- **Compliance dashboard**: 30-day compliance percentage per intervention with progress bars, streak tracking (consecutive days), and color-coded health indicators
+- **Custom interventions**: Add your own supplements or lifestyle practices beyond the curated list with custom units, categories, and frequency
+- **Pause/resume/delete**: Toggle interventions active/inactive without losing log history, or remove entirely
+
+**Server changes**:
+- `server/services/epigenetic.js` — New service with curated interventions database, CRUD for tracked interventions, daily logging with date dedup, compliance/streak calculation
+- `server/lib/genomeValidation.js` — Added Zod schemas for intervention add/update/log
+- `server/routes/genome.js` — 7 new REST endpoints for epigenetic tracking (interventions CRUD, logging, recommendations, compliance)
+
+**Client changes**:
+- `client/src/components/digital-twin/EpigeneticTracker.jsx` — Full-featured tracking UI with compliance bars, daily logging, curated recommendations with expandable details, custom intervention form
+- `client/src/components/digital-twin/tabs/GenomeTab.jsx` — Integrated EpigeneticTracker component between curated markers and ClinVar sections
+- `client/src/services/api.js` — Added 7 epigenetic API functions
+
### Digital Twin — CLI Provider Support for All AI Functions
- **Unified provider dispatch**: Refactored 8 functions in `digital-twin.js` that had direct `fetch()` calls to `provider.endpoint` (API-only) to use the existing `callProviderAI()` helper which supports both API and CLI providers
- **Affected functions**: `runSingleTest`, `scoreTestResponse`, `generateEnrichmentQuestion`, `analyzeEnrichmentList`, `detectContradictions`, `generateDynamicTests`, `analyzeWritingSamples`, `extractTraits`, `calculateConfidence`, `analyzeWithPrompt`
diff --git a/client/src/components/digital-twin/EpigeneticTracker.jsx b/client/src/components/digital-twin/EpigeneticTracker.jsx
new file mode 100644
index 0000000000..f19a76ddbf
--- /dev/null
+++ b/client/src/components/digital-twin/EpigeneticTracker.jsx
@@ -0,0 +1,407 @@
+import { useState, useEffect, useCallback } from 'react';
+import toast from 'react-hot-toast';
+import {
+ Plus, RefreshCw, Trash2, ChevronDown, ChevronRight,
+ Activity, Pill, Heart, CheckCircle, Calendar, FlameKindling
+} from 'lucide-react';
+import * as api from '../../services/api';
+
+const CATEGORY_ICONS = {
+ supplement: Pill,
+ lifestyle: Heart,
+ custom: Activity
+};
+
+const EVIDENCE_COLORS = {
+ strong: 'bg-green-500/20 text-green-400 border-green-500/30',
+ moderate: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
+ emerging: 'bg-blue-500/20 text-blue-400 border-blue-500/30'
+};
+
+export default function EpigeneticTracker({ markerCategories = [] }) {
+ const [interventions, setInterventions] = useState({});
+ const [recommendations, setRecommendations] = useState([]);
+ const [compliance, setCompliance] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [showAdd, setShowAdd] = useState(false);
+ const [expandedRecs, setExpandedRecs] = useState({});
+ const [expandedTracked, setExpandedTracked] = useState({});
+ const [logAmounts, setLogAmounts] = useState({});
+ const [loggingId, setLoggingId] = useState(null);
+
+ // Custom intervention form
+ const [customForm, setCustomForm] = useState({
+ name: '', category: 'supplement', dosage: '', frequency: 'daily', trackingUnit: 'mg', notes: ''
+ });
+
+ const fetchData = useCallback(async () => {
+ const [intData, recData, compData] = await Promise.all([
+ api.getEpigeneticInterventions().catch(() => ({ interventions: {} })),
+ api.getEpigeneticRecommendations(markerCategories).catch(() => ({ recommendations: [] })),
+ api.getEpigeneticCompliance(30).catch(() => null)
+ ]);
+ setInterventions(intData.interventions || {});
+ setRecommendations(recData.recommendations || []);
+ setCompliance(compData);
+ setLoading(false);
+ }, [markerCategories]);
+
+ useEffect(() => { fetchData(); }, [fetchData]);
+
+ const handleAddCurated = useCallback(async (rec) => {
+ const result = await api.addEpigeneticIntervention({
+ id: rec.id,
+ name: rec.name,
+ category: rec.category,
+ dosage: rec.dosageRange?.optimal || '',
+ frequency: 'daily',
+ trackingUnit: rec.trackingUnit,
+ notes: ''
+ }).catch(() => null);
+ if (result) {
+ toast.success(`Tracking ${rec.name}`);
+ await fetchData();
+ }
+ }, [fetchData]);
+
+ const handleAddCustom = useCallback(async () => {
+ if (!customForm.name.trim()) {
+ toast.error('Name is required');
+ return;
+ }
+ const result = await api.addEpigeneticIntervention(customForm).catch(() => null);
+ if (result) {
+ toast.success(`Tracking ${customForm.name}`);
+ setCustomForm({ name: '', category: 'supplement', dosage: '', frequency: 'daily', trackingUnit: 'mg', notes: '' });
+ setShowAdd(false);
+ await fetchData();
+ }
+ }, [customForm, fetchData]);
+
+ const handleLog = useCallback(async (id) => {
+ const amount = parseFloat(logAmounts[id]);
+ if (isNaN(amount) || amount < 0) {
+ toast.error('Enter a valid amount');
+ return;
+ }
+ setLoggingId(id);
+ const result = await api.logEpigeneticEntry(id, { amount }).catch(() => null);
+ if (result) {
+ toast.success('Logged');
+ setLogAmounts(prev => ({ ...prev, [id]: '' }));
+ await fetchData();
+ }
+ setLoggingId(null);
+ }, [logAmounts, fetchData]);
+
+ const handleToggleActive = useCallback(async (id, active) => {
+ await api.updateEpigeneticIntervention(id, { active: !active }).catch(() => null);
+ await fetchData();
+ }, [fetchData]);
+
+ const handleDelete = useCallback(async (id, name) => {
+ await api.deleteEpigeneticIntervention(id).catch(() => null);
+ toast.success(`Removed ${name}`);
+ await fetchData();
+ }, [fetchData]);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center py-8">
+ <RefreshCw className="w-5 h-5 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ const trackedList = Object.entries(interventions);
+ const trackedIds = new Set(trackedList.map(([, i]) => i.id));
+ const untrackedRecs = recommendations.filter(r => !trackedIds.has(r.id));
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div className="flex items-center justify-between flex-wrap gap-2">
+ <div>
+ <h3 className="text-lg font-semibold text-white flex items-center gap-2">
+ <FlameKindling size={20} className="text-orange-400" />
+ Epigenetic Lifestyle Interventions
+ </h3>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Track neuroprotective supplements and lifestyle practices that modify genetic risk through epigenetic mechanisms.
+ </p>
+ </div>
+ <button
+ onClick={() => setShowAdd(!showAdd)}
+ className="flex items-center gap-1.5 px-3 py-2 bg-port-accent/20 text-port-accent border border-port-accent/30 rounded text-sm hover:bg-port-accent/30 transition-colors"
+ >
+ <Plus size={14} />
+ Custom Intervention
+ </button>
+ </div>
+
+ {/* Custom Intervention Form */}
+ {showAdd && (
+ <div className="p-4 rounded bg-port-card border border-port-border space-y-3">
+ <h4 className="text-sm font-medium text-white">Add Custom Intervention</h4>
+ <div className="grid grid-cols-2 gap-3">
+ <input
+ type="text"
+ value={customForm.name}
+ onChange={(e) => setCustomForm(prev => ({ ...prev, name: e.target.value }))}
+ placeholder="Intervention name"
+ className="col-span-2 px-3 py-2 bg-port-bg border border-port-border rounded text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent"
+ />
+ <select
+ value={customForm.category}
+ onChange={(e) => setCustomForm(prev => ({ ...prev, category: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-sm text-white focus:outline-none"
+ >
+ <option value="supplement">Supplement</option>
+ <option value="lifestyle">Lifestyle</option>
+ <option value="custom">Custom</option>
+ </select>
+ <select
+ value={customForm.frequency}
+ onChange={(e) => setCustomForm(prev => ({ ...prev, frequency: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-sm text-white focus:outline-none"
+ >
+ <option value="daily">Daily</option>
+ <option value="weekly">Weekly</option>
+ <option value="as_needed">As Needed</option>
+ </select>
+ <input
+ type="text"
+ value={customForm.dosage}
+ onChange={(e) => setCustomForm(prev => ({ ...prev, dosage: e.target.value }))}
+ placeholder="Target dosage (e.g. 5g/day)"
+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-sm text-white placeholder-gray-600 focus:outline-none"
+ />
+ <input
+ type="text"
+ value={customForm.trackingUnit}
+ onChange={(e) => setCustomForm(prev => ({ ...prev, trackingUnit: e.target.value }))}
+ placeholder="Unit (g, mg, min, etc.)"
+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-sm text-white placeholder-gray-600 focus:outline-none"
+ />
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={handleAddCustom}
+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent border border-port-accent/30 rounded text-sm hover:bg-port-accent/30"
+ >
+ Add
+ </button>
+ <button
+ onClick={() => setShowAdd(false)}
+ className="px-3 py-1.5 bg-port-card border border-port-border rounded text-sm text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Compliance Summary */}
+ {compliance && Object.keys(compliance.summary).length > 0 && (
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ {Object.entries(compliance.summary).map(([id, s]) => (
+ <div key={id} className="p-3 rounded bg-port-card border border-port-border">
+ <div className="text-xs text-gray-500 truncate">{s.name}</div>
+ <div className="flex items-center gap-2 mt-1">
+ <div className="flex-1 h-1.5 bg-port-bg rounded-full overflow-hidden">
+ <div
+ className={`h-full rounded-full transition-all ${
+ s.compliance >= 0.8 ? 'bg-green-500' :
+ s.compliance >= 0.5 ? 'bg-yellow-500' : 'bg-red-500'
+ }`}
+ style={{ width: `${Math.round(s.compliance * 100)}%` }}
+ />
+ </div>
+ <span className="text-xs font-mono text-white">{Math.round(s.compliance * 100)}%</span>
+ </div>
+ {s.streak > 0 && (
+ <div className="text-xs text-orange-400 mt-1 flex items-center gap-1">
+ <FlameKindling size={10} />
+ {s.streak}d streak
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Currently Tracked */}
+ {trackedList.length > 0 && (
+ <div className="space-y-2">
+ <h4 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Tracking ({trackedList.length})</h4>
+ {trackedList.map(([key, intervention]) => {
+ const Icon = CATEGORY_ICONS[intervention.category] || Activity;
+ const isExpanded = expandedTracked[key];
+ const recentLogs = intervention.logs?.slice(-7) || [];
+
+ return (
+ <div key={key} className="rounded bg-port-card border border-port-border overflow-hidden">
+ <button
+ onClick={() => setExpandedTracked(prev => ({ ...prev, [key]: !prev[key] }))}
+ className="w-full flex items-center gap-3 p-3 text-left hover:bg-white/5 transition-colors"
+ >
+ <Icon size={16} className={intervention.active ? 'text-green-400' : 'text-gray-600'} />
+ <span className={`text-sm font-medium flex-1 ${intervention.active ? 'text-white' : 'text-gray-500'}`}>
+ {intervention.name}
+ </span>
+ {intervention.dosage && (
+ <span className="text-xs text-gray-500">{intervention.dosage}</span>
+ )}
+ <span className="text-xs text-gray-600">{intervention.frequency}</span>
+ {isExpanded ? <ChevronDown size={14} className="text-gray-500" /> : <ChevronRight size={14} className="text-gray-500" />}
+ </button>
+
+ {isExpanded && (
+ <div className="px-3 pb-3 space-y-3 border-t border-port-border/50">
+ {/* Quick log */}
+ <div className="flex items-center gap-2 mt-3">
+ <input
+ type="number"
+ value={logAmounts[key] || ''}
+ onChange={(e) => setLogAmounts(prev => ({ ...prev, [key]: e.target.value }))}
+ onKeyDown={(e) => e.key === 'Enter' && handleLog(key)}
+ placeholder={`Amount (${intervention.trackingUnit})`}
+ className="flex-1 max-w-[160px] px-3 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent font-mono"
+ min="0"
+ step="any"
+ />
+ <span className="text-xs text-gray-500">{intervention.trackingUnit}</span>
+ <button
+ onClick={() => handleLog(key)}
+ disabled={loggingId === key}
+ className="flex items-center gap-1 px-3 py-1.5 bg-green-500/20 text-green-400 border border-green-500/30 rounded text-sm hover:bg-green-500/30 disabled:opacity-50"
+ >
+ {loggingId === key ? <RefreshCw size={12} className="animate-spin" /> : <CheckCircle size={12} />}
+ Log Today
+ </button>
+ </div>
+
+ {/* Recent log history */}
+ {recentLogs.length > 0 && (
+ <div className="flex gap-1 items-end">
+ <Calendar size={12} className="text-gray-600 mb-0.5" />
+ <div className="flex gap-1">
+ {recentLogs.map(log => (
+ <div
+ key={log.id}
+ title={`${log.date}: ${log.amount} ${log.unit}`}
+ className="w-6 h-6 rounded bg-green-500/20 border border-green-500/30 flex items-center justify-center text-[10px] text-green-400 font-mono"
+ >
+ {log.amount}
+ </div>
+ ))}
+ </div>
+ <span className="text-[10px] text-gray-600 ml-1">last 7 entries</span>
+ </div>
+ )}
+
+ {/* Actions */}
+ <div className="flex gap-2 text-xs">
+ <button
+ onClick={() => handleToggleActive(key, intervention.active)}
+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-gray-400 hover:text-white"
+ >
+ {intervention.active ? 'Pause' : 'Resume'}
+ </button>
+ <button
+ onClick={() => handleDelete(key, intervention.name)}
+ className="px-2 py-1 bg-red-500/10 border border-red-500/20 rounded text-red-400 hover:bg-red-500/20"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Recommended Interventions (not yet tracked) */}
+ {untrackedRecs.length > 0 && (
+ <div className="space-y-2">
+ <h4 className="text-sm font-medium text-gray-400 uppercase tracking-wider">
+ Recommended Interventions ({untrackedRecs.length})
+ </h4>
+ <p className="text-xs text-gray-600">
+ Evidence-based interventions targeting your genetic risk markers. Click to learn more and start tracking.
+ </p>
+ {untrackedRecs.map(rec => {
+ const Icon = CATEGORY_ICONS[rec.category] || Activity;
+ const isExpanded = expandedRecs[rec.id];
+
+ return (
+ <div key={rec.id} className="rounded bg-port-card border border-port-border overflow-hidden">
+ <button
+ onClick={() => setExpandedRecs(prev => ({ ...prev, [rec.id]: !prev[rec.id] }))}
+ className="w-full flex items-center gap-3 p-3 text-left hover:bg-white/5 transition-colors"
+ >
+ <Icon size={16} className="text-purple-400" />
+ <span className="text-sm font-medium text-white flex-1">{rec.name}</span>
+ <span className={`px-1.5 py-0.5 rounded text-xs border ${EVIDENCE_COLORS[rec.evidenceLevel] || EVIDENCE_COLORS.emerging}`}>
+ {rec.evidenceLevel}
+ </span>
+ {isExpanded ? <ChevronDown size={14} className="text-gray-500" /> : <ChevronRight size={14} className="text-gray-500" />}
+ </button>
+
+ {isExpanded && (
+ <div className="px-3 pb-3 space-y-3 border-t border-port-border/50">
+ <p className="text-sm text-gray-400 mt-2">{rec.mechanism}</p>
+
+ <div className="flex flex-wrap gap-3 text-xs">
+ <div>
+ <span className="text-gray-500">Optimal: </span>
+ <span className="text-white">{rec.dosageRange?.optimal}</span>
+ </div>
+ <div>
+ <span className="text-gray-500">Range: </span>
+ <span className="text-white">{rec.dosageRange?.min}–{rec.dosageRange?.max} {rec.dosageRange?.unit}</span>
+ </div>
+ <div>
+ <span className="text-gray-500">Targets: </span>
+ <span className="text-purple-400">{rec.targetMarkers.join(', ')}</span>
+ </div>
+ </div>
+
+ {rec.references?.length > 0 && (
+ <div className="text-xs text-gray-600 space-y-0.5">
+ {rec.references.map((ref, i) => (
+ <div key={i}>{ref}</div>
+ ))}
+ </div>
+ )}
+
+ <button
+ onClick={() => handleAddCurated(rec)}
+ className="flex items-center gap-1.5 px-3 py-1.5 bg-purple-500/20 text-purple-400 border border-purple-500/30 rounded text-sm hover:bg-purple-500/30"
+ >
+ <Plus size={14} />
+ Start Tracking
+ </button>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {trackedList.length === 0 && untrackedRecs.length === 0 && (
+ <div className="text-center py-6 text-gray-500 text-sm">
+ <FlameKindling className="w-8 h-8 mx-auto mb-2 opacity-50" />
+ <p>Upload genome data and scan markers to get personalized neuroprotective recommendations.</p>
+ </div>
+ )}
+
+ <p className="text-xs text-gray-600">
+ These recommendations are informational — consult a healthcare provider before starting any supplementation program.
+ </p>
+ </div>
+ );
+}
diff --git a/client/src/components/digital-twin/tabs/GenomeTab.jsx b/client/src/components/digital-twin/tabs/GenomeTab.jsx
index f6a52c7726..50c99c2b6c 100644
--- a/client/src/components/digital-twin/tabs/GenomeTab.jsx
+++ b/client/src/components/digital-twin/tabs/GenomeTab.jsx
@@ -6,6 +6,7 @@ import {
import { unzipSync, strFromU8 } from 'fflate';
import * as api from '../../../services/api';
import GenomeCategoryCard from '../GenomeCategoryCard';
+import EpigeneticTracker from '../EpigeneticTracker';
const CATEGORY_META = {
longevity: { emoji: '\u2728', label: 'Longevity', color: 'purple' },
@@ -18,6 +19,7 @@ const CATEGORY_META = {
inflammation: { emoji: '\u{1F525}', label: 'Inflammation', color: 'orange' },
tumor_suppression: { emoji: '\u{1F9EC}', label: 'Tumor Suppression', color: 'indigo' },
cognitive: { emoji: '\u{1F9E0}', label: 'Cognitive', color: 'cyan' },
+ cognitive_decline: { emoji: '\u{1F9D3}', label: 'Cognitive Decline & Dementia Risk', color: 'rose' },
sleep: { emoji: '\u{1F319}', label: 'Sleep & Circadian', color: 'violet' },
athletic: { emoji: '\u{1F4AA}', label: 'Athletic Performance', color: 'sky' },
skin: { emoji: '\u2600\uFE0F', label: 'Skin & UV Response', color: 'yellow' }
@@ -325,7 +327,7 @@ export default function GenomeTab() {
}
// Sort categories by a defined order
- const categoryOrder = ['longevity', 'cardiovascular', 'tumor_suppression', 'iron', 'methylation', 'nutrient', 'cognitive', 'caffeine', 'sleep', 'athletic', 'detox', 'inflammation', 'skin'];
+ const categoryOrder = ['longevity', 'cardiovascular', 'tumor_suppression', 'cognitive_decline', 'iron', 'methylation', 'nutrient', 'cognitive', 'caffeine', 'sleep', 'athletic', 'detox', 'inflammation', 'skin'];
const sortedCategories = Object.keys(grouped).sort((a, b) => {
const ai = categoryOrder.indexOf(a);
const bi = categoryOrder.indexOf(b);
@@ -441,10 +443,17 @@ export default function GenomeTab() {
{markers.length === 0 && (
<div className="text-center py-8 text-gray-500">
<Dna className="w-10 h-10 mx-auto mb-3 opacity-50" />
- <p>No markers saved yet. Click "Scan Known Markers" to analyze your genome against 30 curated health markers.</p>
+ <p>No markers saved yet. Click "Scan Known Markers" to analyze your genome against curated health markers.</p>
</div>
)}
+ {/* Epigenetic Lifestyle Tracking */}
+ <div className="border-t border-port-border pt-6">
+ <EpigeneticTracker
+ markerCategories={[...new Set(markers.map(m => m.category).filter(Boolean))]}
+ />
+ </div>
+
{/* ClinVar Database section */}
<div className="border-t border-port-border pt-6 space-y-4">
<div className="flex items-center justify-between flex-wrap gap-2">
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 0b572d4f04..d37a6de857 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1026,6 +1026,28 @@ export const syncClinvar = () => request('/digital-twin/genome/clinvar/sync', {
export const scanClinvar = () => request('/digital-twin/genome/clinvar/scan', { method: 'POST' });
export const deleteClinvar = () => request('/digital-twin/genome/clinvar', { method: 'DELETE' });
+// Digital Twin - Epigenetic Lifestyle Tracking
+export const getEpigeneticInterventions = () => request('/digital-twin/genome/epigenetic');
+export const getEpigeneticRecommendations = (categories = []) =>
+ request(`/digital-twin/genome/epigenetic/recommendations${categories.length ? `?categories=${categories.join(',')}` : ''}`);
+export const getEpigeneticCompliance = (days = 30) =>
+ request(`/digital-twin/genome/epigenetic/compliance?days=${days}`);
+export const addEpigeneticIntervention = (data) => request('/digital-twin/genome/epigenetic', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const logEpigeneticEntry = (id, entry) => request(`/digital-twin/genome/epigenetic/${id}/log`, {
+ method: 'POST',
+ body: JSON.stringify(entry)
+});
+export const updateEpigeneticIntervention = (id, updates) => request(`/digital-twin/genome/epigenetic/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(updates)
+});
+export const deleteEpigeneticIntervention = (id) => request(`/digital-twin/genome/epigenetic/${id}`, {
+ method: 'DELETE'
+});
+
// Browser - CDP browser management
export const getBrowserStatus = () => request('/browser');
export const getBrowserConfig = () => request('/browser/config');
diff --git a/server/lib/curatedGenomeMarkers.js b/server/lib/curatedGenomeMarkers.js
index 04fdc84159..ca86132862 100644
--- a/server/lib/curatedGenomeMarkers.js
+++ b/server/lib/curatedGenomeMarkers.js
@@ -14,6 +14,7 @@ export const MARKER_CATEGORIES = {
inflammation: { label: 'Inflammation', icon: 'Flame', color: 'orange' },
tumor_suppression: { label: 'Tumor Suppression', icon: 'ShieldCheck', color: 'indigo' },
cognitive: { label: 'Cognitive', icon: 'Brain', color: 'cyan' },
+ cognitive_decline: { label: 'Cognitive Decline & Dementia Risk', icon: 'BrainCog', color: 'rose' },
sleep: { label: 'Sleep & Circadian', icon: 'Moon', color: 'violet' },
athletic: { label: 'Athletic Performance', icon: 'Dumbbell', color: 'sky' },
skin: { label: 'Skin & UV Response', icon: 'Sun', color: 'yellow' }
@@ -528,6 +529,195 @@ export const CURATED_MARKERS = [
]
},
+ // === COGNITIVE DECLINE & DEMENTIA RISK ===
+ {
+ rsid: 'rs429358',
+ gene: 'APOE',
+ name: 'APOE ε4 Alzheimer\'s Risk (rs429358)',
+ category: 'cognitive_decline',
+ description: 'APOE ε4 is the strongest common genetic risk factor for late-onset Alzheimer\'s disease. The ε4 allele (T→C at rs429358) impairs amyloid-beta clearance. One copy increases risk ~3x; two copies increase risk ~12x. APOE genotype is determined by the combination of rs429358 and rs7412.',
+ implications: {
+ beneficial: 'T/T — no ε4 allele at this position. Lower baseline Alzheimer\'s risk from APOE.',
+ concern: 'C/T — one ε4 allele. ~3x increased Alzheimer\'s risk. Prioritize neuroprotective lifestyle (exercise, sleep, omega-3, creatine).',
+ major_concern: 'C/C — two ε4 alleles (ε4/ε4). ~12x increased Alzheimer\'s risk. Aggressive neuroprotective strategy strongly recommended. Consider early cognitive monitoring.'
+ },
+ rules: [
+ { genotypes: ['T/T'], status: 'beneficial' },
+ { genotypes: ['C/T', 'T/C'], status: 'concern' },
+ { genotypes: ['C/C'], status: 'major_concern' }
+ ]
+ },
+ {
+ rsid: 'rs7412',
+ gene: 'APOE',
+ name: 'APOE ε2 Protective Variant (rs7412)',
+ category: 'cognitive_decline',
+ description: 'APOE ε2 is the protective counterpart to ε4. The ε2 allele (C→T at rs7412) is associated with better amyloid clearance and ~40% reduced Alzheimer\'s risk. ε2/ε2 carriers have the lowest risk; ε2/ε3 carriers still benefit.',
+ implications: {
+ beneficial: 'T/T — ε2/ε2. Strongest APOE-mediated neuroprotection. Significantly reduced Alzheimer\'s risk.',
+ typical: 'C/T — one ε2 allele. ~40% reduced Alzheimer\'s risk compared to ε3/ε3.',
+ concern: 'C/C — no ε2 allele. Standard risk (modified by rs429358 ε4 status).'
+ },
+ rules: [
+ { genotypes: ['T/T'], status: 'beneficial' },
+ { genotypes: ['C/T', 'T/C'], status: 'typical' },
+ { genotypes: ['C/C'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs3865444',
+ gene: 'CD33',
+ name: 'CD33 Microglial Clearance',
+ category: 'cognitive_decline',
+ description: 'CD33 is expressed on microglia and regulates amyloid-beta phagocytosis. The A allele reduces CD33 surface expression, enhancing microglial clearance of amyloid plaques. Replicated across multiple GWAS for Alzheimer\'s risk.',
+ implications: {
+ beneficial: 'A/A — reduced CD33 expression. Enhanced microglial amyloid clearance. Lower Alzheimer\'s risk.',
+ typical: 'A/C — intermediate CD33 levels. Moderate clearance capacity.',
+ concern: 'C/C — higher CD33 expression. Reduced amyloid clearance by microglia.'
+ },
+ rules: [
+ { genotypes: ['A/A'], status: 'beneficial' },
+ { genotypes: ['A/C', 'C/A'], status: 'typical' },
+ { genotypes: ['C/C'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs3764650',
+ gene: 'ABCA7',
+ name: 'ABCA7 Lipid Transport & Amyloid',
+ category: 'cognitive_decline',
+ description: 'ABCA7 is involved in lipid transport and amyloid precursor protein processing. Loss-of-function variants increase Alzheimer\'s risk ~1.8x, particularly in African-ancestry populations where the effect is stronger.',
+ implications: {
+ beneficial: 'G/G — normal ABCA7 function. Standard lipid transport and amyloid processing.',
+ typical: 'G/T — one risk allele. Mildly elevated Alzheimer\'s risk.',
+ concern: 'T/T — reduced ABCA7 function. ~1.8x increased Alzheimer\'s risk.'
+ },
+ rules: [
+ { genotypes: ['G/G'], status: 'beneficial' },
+ { genotypes: ['G/T', 'T/G'], status: 'typical' },
+ { genotypes: ['T/T'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs6656401',
+ gene: 'CR1',
+ name: 'Complement Receptor 1 (Neuroinflammation)',
+ category: 'cognitive_decline',
+ description: 'CR1 encodes complement receptor 1, part of the innate immune system. The A allele is associated with increased amyloid-beta deposition and neuroinflammation, contributing to Alzheimer\'s risk (~1.2x per allele).',
+ implications: {
+ beneficial: 'G/G — standard CR1 expression. Normal complement-mediated clearance.',
+ typical: 'A/G — one risk allele. Slightly elevated neuroinflammation risk.',
+ concern: 'A/A — elevated CR1 risk. Associated with increased amyloid burden and neuroinflammation.'
+ },
+ rules: [
+ { genotypes: ['G/G'], status: 'beneficial' },
+ { genotypes: ['A/G', 'G/A'], status: 'typical' },
+ { genotypes: ['A/A'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs11136000',
+ gene: 'CLU',
+ name: 'Clusterin (Apolipoprotein J)',
+ category: 'cognitive_decline',
+ description: 'CLU (clusterin/apolipoprotein J) is a chaperone protein that binds amyloid-beta and facilitates its clearance across the blood-brain barrier. The T allele is protective, associated with better amyloid clearance.',
+ implications: {
+ beneficial: 'T/T — protective genotype. Enhanced clusterin-mediated amyloid clearance.',
+ typical: 'C/T — intermediate effect. Standard clusterin function.',
+ concern: 'C/C — reduced clusterin efficiency. Mildly elevated amyloid accumulation risk.'
+ },
+ rules: [
+ { genotypes: ['T/T'], status: 'beneficial' },
+ { genotypes: ['C/T', 'T/C'], status: 'typical' },
+ { genotypes: ['C/C'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs744373',
+ gene: 'BIN1',
+ name: 'BIN1 Tau & Synaptic Function',
+ category: 'cognitive_decline',
+ description: 'BIN1 (bridging integrator 1) is the second strongest Alzheimer\'s risk locus after APOE. It\'s involved in tau pathology, synaptic vesicle recycling, and endocytosis. The C allele increases risk ~1.2x per copy.',
+ implications: {
+ beneficial: 'T/T — lower BIN1-mediated Alzheimer\'s risk. Normal synaptic function.',
+ typical: 'C/T — one risk allele. Slightly elevated risk.',
+ concern: 'C/C — elevated BIN1 risk. Associated with increased tau pathology and synaptic dysfunction.'
+ },
+ rules: [
+ { genotypes: ['T/T'], status: 'beneficial' },
+ { genotypes: ['C/T', 'T/C'], status: 'typical' },
+ { genotypes: ['C/C'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs9349407',
+ gene: 'PICALM',
+ name: 'PICALM Endocytic Clearance',
+ category: 'cognitive_decline',
+ description: 'PICALM mediates clathrin-mediated endocytosis and amyloid-beta clearance across the blood-brain barrier. Variants affect the efficiency of cellular waste removal in the brain.',
+ implications: {
+ beneficial: 'C/C — efficient PICALM function. Better endocytic clearance of amyloid.',
+ typical: 'C/G — intermediate clearance capacity.',
+ concern: 'G/G — reduced PICALM efficiency. Impaired endocytic amyloid clearance.'
+ },
+ rules: [
+ { genotypes: ['C/C'], status: 'beneficial' },
+ { genotypes: ['C/G', 'G/C'], status: 'typical' },
+ { genotypes: ['G/G'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs3851179',
+ gene: 'PICALM',
+ name: 'PICALM Protective Variant',
+ category: 'cognitive_decline',
+ description: 'This PICALM variant is independently protective against Alzheimer\'s. The A allele enhances autophagy and tau clearance, reducing accumulation of toxic protein aggregates.',
+ implications: {
+ beneficial: 'A/A — enhanced autophagy and tau clearance. Protective against Alzheimer\'s.',
+ typical: 'A/G — intermediate protective effect.',
+ concern: 'G/G — standard PICALM autophagy function. No additional protection.'
+ },
+ rules: [
+ { genotypes: ['A/A'], status: 'beneficial' },
+ { genotypes: ['A/G', 'G/A'], status: 'typical' },
+ { genotypes: ['G/G'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs10948363',
+ gene: 'CD2AP',
+ name: 'CD2AP Blood-Brain Barrier Integrity',
+ category: 'cognitive_decline',
+ description: 'CD2AP maintains blood-brain barrier integrity and supports synaptic function. Variants are associated with Alzheimer\'s risk through impaired BBB function and increased neuroinflammation.',
+ implications: {
+ beneficial: 'A/A — normal CD2AP function. Intact blood-brain barrier support.',
+ typical: 'A/G — intermediate BBB risk.',
+ concern: 'G/G — reduced CD2AP function. Associated with BBB dysfunction and elevated Alzheimer\'s risk.'
+ },
+ rules: [
+ { genotypes: ['A/A'], status: 'beneficial' },
+ { genotypes: ['A/G', 'G/A'], status: 'typical' },
+ { genotypes: ['G/G'], status: 'concern' }
+ ]
+ },
+ {
+ rsid: 'rs983392',
+ gene: 'MS4A6A',
+ name: 'MS4A6A Microglial Activation',
+ category: 'cognitive_decline',
+ description: 'MS4A6A is part of the membrane-spanning 4A gene cluster expressed in myeloid cells. Variants affect microglial activation patterns and soluble TREM2 levels, both relevant to Alzheimer\'s neuroinflammation.',
+ implications: {
+ beneficial: 'A/A — protective microglial activation pattern. Higher soluble TREM2.',
+ typical: 'A/G — intermediate microglial function.',
+ concern: 'G/G — altered microglial activation. Lower soluble TREM2 associated with increased neuroinflammation.'
+ },
+ rules: [
+ { genotypes: ['A/A'], status: 'beneficial' },
+ { genotypes: ['A/G', 'G/A'], status: 'typical' },
+ { genotypes: ['G/G'], status: 'concern' }
+ ]
+ },
+
// === SLEEP & CIRCADIAN ===
{
rsid: 'rs1801260',
diff --git a/server/lib/genomeValidation.js b/server/lib/genomeValidation.js
index 2bed85c10e..4cfb053e7e 100644
--- a/server/lib/genomeValidation.js
+++ b/server/lib/genomeValidation.js
@@ -27,3 +27,29 @@ export const genomeSaveMarkerSchema = z.object({
export const genomeUpdateNotesSchema = z.object({
notes: z.string().max(5000)
});
+
+// === Epigenetic Lifestyle Tracking ===
+
+export const epigeneticAddInterventionSchema = z.object({
+ id: z.string().min(1).max(100).optional(),
+ name: z.string().min(1).max(200),
+ category: z.enum(['supplement', 'lifestyle', 'custom']).default('custom'),
+ dosage: z.string().max(200).optional().default(''),
+ frequency: z.enum(['daily', 'weekly', 'as_needed']).default('daily'),
+ trackingUnit: z.string().min(1).max(50).default('dose'),
+ notes: z.string().max(5000).optional().default('')
+});
+
+export const epigeneticLogEntrySchema = z.object({
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD format').optional(),
+ amount: z.number().min(0),
+ notes: z.string().max(2000).optional().default('')
+});
+
+export const epigeneticUpdateInterventionSchema = z.object({
+ name: z.string().min(1).max(200).optional(),
+ dosage: z.string().max(200).optional(),
+ frequency: z.enum(['daily', 'weekly', 'as_needed']).optional(),
+ notes: z.string().max(5000).optional(),
+ active: z.boolean().optional()
+});
diff --git a/server/routes/genome.js b/server/routes/genome.js
index ab29e6c8f3..9c4dcf8bae 100644
--- a/server/routes/genome.js
+++ b/server/routes/genome.js
@@ -1,13 +1,17 @@
import { Router } from 'express';
import * as genomeService from '../services/genome.js';
import * as clinvarService from '../services/clinvar.js';
+import * as epigeneticService from '../services/epigenetic.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validate } from '../lib/validation.js';
import {
genomeUploadSchema,
genomeSearchSchema,
genomeSaveMarkerSchema,
- genomeUpdateNotesSchema
+ genomeUpdateNotesSchema,
+ epigeneticAddInterventionSchema,
+ epigeneticLogEntrySchema,
+ epigeneticUpdateInterventionSchema
} from '../lib/genomeValidation.js';
const router = Router();
@@ -172,6 +176,100 @@ router.delete('/clinvar', asyncHandler(async (req, res) => {
res.status(204).end();
}));
+// === Epigenetic Lifestyle Tracking Routes ===
+
+// GET /api/digital-twin/genome/epigenetic — Get tracked interventions
+router.get('/epigenetic', asyncHandler(async (req, res) => {
+ const data = await epigeneticService.getInterventions();
+ res.json(data);
+}));
+
+// GET /api/digital-twin/genome/epigenetic/recommendations — Get curated recommendations
+router.get('/epigenetic/recommendations', asyncHandler(async (req, res) => {
+ const categories = req.query.categories ? req.query.categories.split(',') : [];
+ const recommendations = epigeneticService.getRecommendations(categories);
+ res.json({ recommendations });
+}));
+
+// GET /api/digital-twin/genome/epigenetic/compliance — Get compliance summary
+router.get('/epigenetic/compliance', asyncHandler(async (req, res) => {
+ const days = parseInt(req.query.days) || 30;
+ const summary = await epigeneticService.getComplianceSummary(days);
+ res.json(summary);
+}));
+
+// POST /api/digital-twin/genome/epigenetic — Add intervention
+router.post('/epigenetic', asyncHandler(async (req, res) => {
+ const validation = validate(epigeneticAddInterventionSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const result = await epigeneticService.addIntervention(validation.data);
+ res.status(201).json(result);
+}));
+
+// POST /api/digital-twin/genome/epigenetic/:id/log — Log daily entry
+router.post('/epigenetic/:id/log', asyncHandler(async (req, res) => {
+ const validation = validate(epigeneticLogEntrySchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const result = await epigeneticService.logEntry(req.params.id, validation.data);
+ if (result.error) {
+ throw new ServerError(result.error, {
+ status: 404,
+ code: 'INTERVENTION_NOT_FOUND'
+ });
+ }
+
+ res.status(201).json(result);
+}));
+
+// PUT /api/digital-twin/genome/epigenetic/:id — Update intervention
+router.put('/epigenetic/:id', asyncHandler(async (req, res) => {
+ const validation = validate(epigeneticUpdateInterventionSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+
+ const result = await epigeneticService.updateIntervention(req.params.id, validation.data);
+ if (result.error) {
+ throw new ServerError(result.error, {
+ status: 404,
+ code: 'INTERVENTION_NOT_FOUND'
+ });
+ }
+
+ res.json(result);
+}));
+
+// DELETE /api/digital-twin/genome/epigenetic/:id — Delete intervention
+router.delete('/epigenetic/:id', asyncHandler(async (req, res) => {
+ const result = await epigeneticService.deleteIntervention(req.params.id);
+ if (result.error) {
+ throw new ServerError(result.error, {
+ status: 404,
+ code: 'INTERVENTION_NOT_FOUND'
+ });
+ }
+
+ res.status(204).end();
+}));
+
// DELETE /api/digital-twin/genome — Delete all genome data
router.delete('/', asyncHandler(async (req, res) => {
await genomeService.deleteGenome();
diff --git a/server/services/epigenetic.js b/server/services/epigenetic.js
new file mode 100644
index 0000000000..9672e581ea
--- /dev/null
+++ b/server/services/epigenetic.js
@@ -0,0 +1,387 @@
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, ensureDir } from '../lib/fileUtils.js';
+
+const DATA_DIR = PATHS.digitalTwin;
+const EPIGENETIC_FILE = join(DATA_DIR, 'epigenetic.json');
+
+const DEFAULT_DATA = {
+ interventions: {},
+ lastUpdated: null
+};
+
+/**
+ * Curated neuroprotective interventions with evidence-based dosage ranges.
+ * Each intervention maps to genetic markers it addresses.
+ */
+export const CURATED_INTERVENTIONS = [
+ {
+ id: 'creatine',
+ name: 'Creatine Monohydrate',
+ category: 'supplement',
+ targetMarkers: ['cognitive_decline', 'cognitive'],
+ mechanism: 'Creatine buffers ATP in the brain, supporting mitochondrial function and cellular energy. Studies show neuroprotective effects against oxidative stress and excitotoxicity. Particularly relevant for APOE ε4 carriers where mitochondrial dysfunction is an early pathological feature.',
+ evidenceLevel: 'strong',
+ dosageRange: { min: 3, max: 25, unit: 'g/day', optimal: '5-20g/day' },
+ trackingUnit: 'g',
+ references: [
+ 'Rae et al. (2003) - Creatine supplementation improves cognitive performance',
+ 'Brosnan & Brosnan (2016) - The creatine kinase system in brain energy metabolism',
+ 'Forbes et al. (2022) - Creatine supplementation and brain health'
+ ]
+ },
+ {
+ id: 'omega3_dha',
+ name: 'Omega-3 DHA',
+ category: 'supplement',
+ targetMarkers: ['cognitive_decline'],
+ mechanism: 'DHA is the primary structural omega-3 in the brain. It reduces neuroinflammation, supports synaptic plasticity, and promotes amyloid-beta clearance. APOE ε4 carriers show impaired brain DHA uptake, requiring higher intake.',
+ evidenceLevel: 'strong',
+ dosageRange: { min: 500, max: 4000, unit: 'mg/day', optimal: '1000-2000mg DHA' },
+ trackingUnit: 'mg',
+ references: [
+ 'Yassine et al. (2017) - APOE genotype modifies DHA brain uptake',
+ 'Cunnane et al. (2013) - Brain fuel metabolism and Alzheimer\'s',
+ 'Freund-Levi et al. (2006) - DHA supplementation in Alzheimer\'s disease'
+ ]
+ },
+ {
+ id: 'exercise_aerobic',
+ name: 'Aerobic Exercise',
+ category: 'lifestyle',
+ targetMarkers: ['cognitive_decline', 'cognitive', 'cardiovascular'],
+ mechanism: 'Aerobic exercise upregulates BDNF (particularly important for Val66Met carriers), promotes hippocampal neurogenesis, reduces neuroinflammation, and improves cerebrovascular function. The strongest modifiable risk factor for dementia prevention.',
+ evidenceLevel: 'strong',
+ dosageRange: { min: 75, max: 300, unit: 'min/week', optimal: '150-200 min/week' },
+ trackingUnit: 'min',
+ references: [
+ 'Erickson et al. (2011) - Exercise increases hippocampal volume',
+ 'Raichlen & Alexander (2017) - Adaptive capacity model of cognitive aging',
+ 'Livingston et al. (2020) - Lancet Commission on dementia prevention'
+ ]
+ },
+ {
+ id: 'sleep_quality',
+ name: 'Sleep Optimization',
+ category: 'lifestyle',
+ targetMarkers: ['cognitive_decline', 'sleep'],
+ mechanism: 'During deep sleep, the glymphatic system clears amyloid-beta and tau from the brain. Poor sleep quality accelerates amyloid accumulation. 7-9 hours with adequate slow-wave sleep is critical for brain waste clearance.',
+ evidenceLevel: 'strong',
+ dosageRange: { min: 7, max: 9, unit: 'hours/night', optimal: '7.5-8.5 hours' },
+ trackingUnit: 'hours',
+ references: [
+ 'Xie et al. (2013) - Glymphatic system and sleep-driven brain waste clearance',
+ 'Shokri-Kojori et al. (2018) - Sleep deprivation increases amyloid-beta accumulation',
+ 'Winer et al. (2020) - Sleep disturbance and Alzheimer\'s pathology'
+ ]
+ },
+ {
+ id: 'vitamin_d',
+ name: 'Vitamin D',
+ category: 'supplement',
+ targetMarkers: ['cognitive_decline', 'nutrient'],
+ mechanism: 'Vitamin D receptors are expressed throughout the brain. Deficiency is associated with accelerated cognitive decline and increased dementia risk. VDR and VDBP gene variants affect required supplementation levels.',
+ evidenceLevel: 'moderate',
+ dosageRange: { min: 1000, max: 5000, unit: 'IU/day', optimal: '2000-4000 IU/day' },
+ trackingUnit: 'IU',
+ references: [
+ 'Littlejohns et al. (2014) - Vitamin D and risk of dementia and Alzheimer\'s',
+ 'Balion et al. (2012) - Vitamin D cognition and dementia meta-analysis'
+ ]
+ },
+ {
+ id: 'meditation',
+ name: 'Meditation / Mindfulness',
+ category: 'lifestyle',
+ targetMarkers: ['cognitive_decline', 'cognitive', 'inflammation'],
+ mechanism: 'Regular meditation reduces cortisol, lowers neuroinflammation, and preserves gray matter volume. Long-term meditators show less age-related cortical thinning and better preserved hippocampal volume.',
+ evidenceLevel: 'moderate',
+ dosageRange: { min: 10, max: 60, unit: 'min/day', optimal: '20-30 min/day' },
+ trackingUnit: 'min',
+ references: [
+ 'Luders et al. (2015) - Meditation and brain aging',
+ 'Creswell et al. (2016) - Mindfulness and inflammatory biomarkers'
+ ]
+ },
+ {
+ id: 'b_vitamins',
+ name: 'B-Vitamin Complex (B6/B9/B12)',
+ category: 'supplement',
+ targetMarkers: ['cognitive_decline', 'methylation'],
+ mechanism: 'B vitamins lower homocysteine, a neurotoxin linked to brain atrophy and dementia. Particularly critical for MTHFR variant carriers who have impaired folate metabolism. Use methylfolate (not folic acid) for MTHFR C677T carriers.',
+ evidenceLevel: 'strong',
+ dosageRange: { min: 1, max: 1, unit: 'complex/day', optimal: 'Methylated B-complex daily' },
+ trackingUnit: 'dose',
+ references: [
+ 'Smith et al. (2010) - B vitamins slow brain atrophy in MCI',
+ 'Douaud et al. (2013) - B vitamins reduce brain atrophy in Alzheimer\'s-vulnerable regions'
+ ]
+ },
+ {
+ id: 'curcumin',
+ name: 'Curcumin (Turmeric Extract)',
+ category: 'supplement',
+ targetMarkers: ['cognitive_decline', 'inflammation'],
+ mechanism: 'Curcumin crosses the blood-brain barrier and reduces neuroinflammation, inhibits amyloid-beta aggregation, and chelates iron. Bioavailability is critical — use piperine-enhanced or liposomal forms.',
+ evidenceLevel: 'moderate',
+ dosageRange: { min: 500, max: 2000, unit: 'mg/day', optimal: '1000mg bioavailable form' },
+ trackingUnit: 'mg',
+ references: [
+ 'Small et al. (2018) - Memory and brain amyloid effects of curcumin',
+ 'Voulgaropoulou et al. (2019) - Curcumin and cognition meta-analysis'
+ ]
+ },
+ {
+ id: 'cognitive_training',
+ name: 'Cognitive Stimulation',
+ category: 'lifestyle',
+ targetMarkers: ['cognitive_decline', 'cognitive'],
+ mechanism: 'Novel cognitive challenges build cognitive reserve — the brain\'s resilience against neurodegeneration. Activities like learning new languages, musical instruments, or complex problem-solving strengthen synaptic networks.',
+ evidenceLevel: 'moderate',
+ dosageRange: { min: 15, max: 60, unit: 'min/day', optimal: '30+ min/day of novel challenges' },
+ trackingUnit: 'min',
+ references: [
+ 'Stern (2012) - Cognitive reserve in ageing and Alzheimer\'s disease',
+ 'Wilson et al. (2013) - Life-span cognitive activity and late-life cognitive decline'
+ ]
+ },
+ {
+ id: 'social_engagement',
+ name: 'Social Engagement',
+ category: 'lifestyle',
+ targetMarkers: ['cognitive_decline'],
+ mechanism: 'Social isolation is a major modifiable dementia risk factor. Regular social interaction stimulates diverse cognitive processes and reduces cortisol-driven neuroinflammation. Effect size comparable to physical exercise.',
+ evidenceLevel: 'strong',
+ dosageRange: { min: 3, max: 7, unit: 'interactions/week', optimal: 'Daily meaningful interaction' },
+ trackingUnit: 'interactions',
+ references: [
+ 'Livingston et al. (2020) - Lancet Commission: social isolation as dementia risk factor',
+ 'Kuiper et al. (2015) - Social relationships and dementia risk meta-analysis'
+ ]
+ },
+ {
+ id: 'magnesium_threonate',
+ name: 'Magnesium L-Threonate',
+ category: 'supplement',
+ targetMarkers: ['cognitive_decline', 'cognitive', 'sleep'],
+ mechanism: 'Magnesium threonate is the only magnesium form shown to significantly increase brain magnesium levels. It enhances synaptic density, supports NMDA receptor function, and improves both short-term and long-term memory.',
+ evidenceLevel: 'moderate',
+ dosageRange: { min: 1000, max: 2000, unit: 'mg/day', optimal: '1500-2000mg before bed' },
+ trackingUnit: 'mg',
+ references: [
+ 'Slutsky et al. (2010) - Enhancement of learning and memory by elevating brain magnesium',
+ 'Liu et al. (2016) - Magnesium-L-threonate and cognitive abilities'
+ ]
+ },
+ {
+ id: 'lions_mane',
+ name: 'Lion\'s Mane Mushroom',
+ category: 'supplement',
+ targetMarkers: ['cognitive_decline', 'cognitive'],
+ mechanism: 'Lion\'s mane contains hericenones and erinacines that stimulate nerve growth factor (NGF) synthesis. NGF is critical for neuronal survival and synaptic plasticity. Particularly relevant for BDNF Met carriers with reduced neurotrophin signaling.',
+ evidenceLevel: 'emerging',
+ dosageRange: { min: 500, max: 3000, unit: 'mg/day', optimal: '1000-2000mg of fruiting body extract' },
+ trackingUnit: 'mg',
+ references: [
+ 'Mori et al. (2009) - Lion\'s mane improves mild cognitive impairment',
+ 'Li et al. (2018) - Neurohealth properties of Hericium erinaceus'
+ ]
+ }
+];
+
+async function loadData() {
+ await ensureDir(DATA_DIR);
+ const raw = await readFile(EPIGENETIC_FILE, 'utf-8').catch(() => null);
+ if (!raw) return { ...DEFAULT_DATA };
+ return JSON.parse(raw);
+}
+
+async function saveData(data) {
+ await ensureDir(DATA_DIR);
+ data.lastUpdated = new Date().toISOString();
+ await writeFile(EPIGENETIC_FILE, JSON.stringify(data, null, 2));
+}
+
+/**
+ * Get all tracked interventions with their logs.
+ */
+export async function getInterventions() {
+ const data = await loadData();
+ return {
+ interventions: data.interventions,
+ lastUpdated: data.lastUpdated,
+ curatedCount: CURATED_INTERVENTIONS.length,
+ trackedCount: Object.keys(data.interventions).length
+ };
+}
+
+/**
+ * Get curated intervention recommendations, optionally filtered by genetic markers present.
+ */
+export function getRecommendations(markerCategories = []) {
+ if (markerCategories.length === 0) return CURATED_INTERVENTIONS;
+ return CURATED_INTERVENTIONS.filter(i =>
+ i.targetMarkers.some(t => markerCategories.includes(t))
+ );
+}
+
+/**
+ * Start tracking an intervention (curated or custom).
+ */
+export async function addIntervention(intervention) {
+ const data = await loadData();
+ const id = intervention.id || randomUUID();
+
+ // Check if it's a curated one
+ const curated = CURATED_INTERVENTIONS.find(c => c.id === id);
+
+ data.interventions[id] = {
+ id,
+ name: intervention.name || curated?.name || 'Unknown',
+ category: intervention.category || curated?.category || 'custom',
+ dosage: intervention.dosage || '',
+ frequency: intervention.frequency || 'daily',
+ trackingUnit: intervention.trackingUnit || curated?.trackingUnit || 'dose',
+ startedAt: new Date().toISOString(),
+ active: true,
+ notes: intervention.notes || '',
+ logs: []
+ };
+
+ await saveData(data);
+ console.log(`🧬 Epigenetic intervention tracked: ${data.interventions[id].name}`);
+ return data.interventions[id];
+}
+
+/**
+ * Log a daily entry for a tracked intervention.
+ */
+export async function logEntry(interventionId, entry) {
+ const data = await loadData();
+ const intervention = data.interventions[interventionId];
+ if (!intervention) return { error: 'Intervention not found' };
+
+ const log = {
+ id: randomUUID(),
+ date: entry.date || new Date().toISOString().split('T')[0],
+ amount: entry.amount,
+ unit: intervention.trackingUnit,
+ notes: entry.notes || '',
+ loggedAt: new Date().toISOString()
+ };
+
+ // Avoid duplicate date entries — update existing
+ const existingIdx = intervention.logs.findIndex(l => l.date === log.date);
+ if (existingIdx >= 0) {
+ intervention.logs[existingIdx] = { ...intervention.logs[existingIdx], ...log };
+ } else {
+ intervention.logs.push(log);
+ }
+
+ // Keep logs sorted by date
+ intervention.logs.sort((a, b) => a.date.localeCompare(b.date));
+
+ await saveData(data);
+ console.log(`🧬 Logged ${log.amount} ${log.unit} of ${intervention.name} for ${log.date}`);
+ return log;
+}
+
+/**
+ * Update an intervention's settings.
+ */
+export async function updateIntervention(interventionId, updates) {
+ const data = await loadData();
+ const intervention = data.interventions[interventionId];
+ if (!intervention) return { error: 'Intervention not found' };
+
+ if (updates.dosage !== undefined) intervention.dosage = updates.dosage;
+ if (updates.frequency !== undefined) intervention.frequency = updates.frequency;
+ if (updates.notes !== undefined) intervention.notes = updates.notes;
+ if (updates.active !== undefined) intervention.active = updates.active;
+ if (updates.name !== undefined) intervention.name = updates.name;
+
+ await saveData(data);
+ console.log(`🧬 Updated intervention: ${intervention.name}`);
+ return intervention;
+}
+
+/**
+ * Delete an intervention and its logs.
+ */
+export async function deleteIntervention(interventionId) {
+ const data = await loadData();
+ if (!data.interventions[interventionId]) return { error: 'Intervention not found' };
+
+ const name = data.interventions[interventionId].name;
+ delete data.interventions[interventionId];
+ await saveData(data);
+ console.log(`🧬 Deleted intervention: ${name}`);
+ return { success: true };
+}
+
+/**
+ * Get compliance summary for tracked interventions over the last N days.
+ */
+export async function getComplianceSummary(days = 30) {
+ const data = await loadData();
+ const today = new Date();
+ const startDate = new Date(today);
+ startDate.setDate(startDate.getDate() - days);
+ const startStr = startDate.toISOString().split('T')[0];
+
+ const summary = {};
+ for (const [id, intervention] of Object.entries(data.interventions)) {
+ if (!intervention.active) continue;
+
+ const recentLogs = intervention.logs.filter(l => l.date >= startStr);
+ const daysCovered = new Set(recentLogs.map(l => l.date)).size;
+ const expectedDays = intervention.frequency === 'daily' ? days
+ : intervention.frequency === 'weekly' ? Math.ceil(days / 7)
+ : days;
+
+ summary[id] = {
+ name: intervention.name,
+ category: intervention.category,
+ compliance: expectedDays > 0 ? Math.min(1, daysCovered / expectedDays) : 0,
+ daysCovered,
+ expectedDays,
+ recentLogCount: recentLogs.length,
+ lastLogged: recentLogs.length > 0 ? recentLogs[recentLogs.length - 1].date : null,
+ streak: calculateStreak(intervention.logs)
+ };
+ }
+
+ return { summary, periodDays: days, startDate: startStr };
+}
+
+/**
+ * Calculate the current consecutive-day streak for an intervention.
+ */
+function calculateStreak(logs) {
+ if (logs.length === 0) return 0;
+
+ const today = new Date().toISOString().split('T')[0];
+ const dates = new Set(logs.map(l => l.date));
+
+ // Check if today or yesterday has an entry (grace period)
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ const yesterdayStr = yesterday.toISOString().split('T')[0];
+
+ if (!dates.has(today) && !dates.has(yesterdayStr)) return 0;
+
+ let streak = 0;
+ const startDate = dates.has(today) ? new Date() : yesterday;
+
+ for (let d = new Date(startDate); ; d.setDate(d.getDate() - 1)) {
+ const dateStr = d.toISOString().split('T')[0];
+ if (dates.has(dateStr)) {
+ streak++;
+ } else {
+ break;
+ }
+ }
+
+ return streak;
+}