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(genome): add Digital Twin genome analysis with 34 curated markers and ClinVar integration
Adam Eivy773e712df5db
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex 02422f281e..10c95e6011 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -215,7 +215,7 @@ This release adds branch management and automated release workflow capabilities- **File upload**: Drag-and-drop or file picker for 23andMe TSV exports (~600K SNPs), parsed and indexed locally with 1-hour in-memory cache for O(1) rsid lookups- **34 curated health markers** across 13 categories: longevity (FOXO3A, IGF1R, CETP, IPMK, FTO), cardiovascular (Factor V Leiden, 9p21, Lp(a), Prothrombin), tumor suppression (TP53), iron metabolism (HFE H63D, C282Y), methylation (MTHFR C677T/A1298C, COMT, AHCY), nutrients (VDR, BCMO1, FUT2, VDBP), cognitive (BDNF), caffeine (ADA, CYP1A2), sleep (CLOCK, DEC2), athletic (ACTN3, ACE), detoxification (CYP2B6, SOD2, CYP2C19, NQO1), inflammation (IL-6, TNF-alpha), and skin (MC1R)- **Genotype classification**: Each marker's genotype is automatically classified as beneficial, typical, concern, or major_concern with evidence-based implications-- **Category-grouped display**: Markers displayed in collapsible cards grouped by health category with color-coded status badges, expandable details, implications, and editable personal notes+- **Category-grouped grid display**: Markers displayed as compact tiles in a responsive grid (1/2/3 columns) within collapsible category cards, each with emoji category headers, color-coded status dots, and click-to-expand detail panels with implications, notes, and location info- **SNP search**: Look up any rsid in your genome data with instant results and optional save-to-markers- **Full CRUD**: Save custom markers, edit notes (with debounced auto-save), delete individual markers, or wipe all genome data with confirmation- **ClinVar database integration**: One-click sync downloads NCBI's ClinVar variant database (~3M variants), stream-parses it to extract clinically significant SNPs (pathogenic, risk factors, drug response, protective), and builds a local search index. Scanning your genome against ClinVar surfaces hundreds of clinically annotated findings with severity levels, associated conditions, and ClinVar review star ratings@@ -223,7 +223,7 @@ This release adds branch management and automated release workflow capabilities- **Privacy-first**: All data stored locally on the server — genome file never leaves the machine**Server changes**:-- `server/lib/curatedGenomeMarkers.js` — Curated SNP database with 15 markers, category config, `classifyGenotype()` and `formatGenotype()` functions+- `server/lib/curatedGenomeMarkers.js` — Curated SNP database with 34 markers across 13 categories, `classifyGenotype()` and `formatGenotype()` functions- `server/lib/genomeValidation.js` — Zod schemas for upload, search, save, and notes update- `server/services/genome.js` — Core service with lazy-loaded in-memory Map index, upload/scan/search/CRUD/delete operations- `server/services/clinvar.js` — ClinVar sync pipeline: streaming download of variant_summary.txt.gz from NCBI, gunzip + line-by-line parse, filtered index of actionable SNPs, genome cross-reference scan@@ -237,6 +237,10 @@ This release adds branch management and automated release workflow capabilities## Fixes+### ClinVar Header Parsing — Zero Variants Parsed+- **Fix**: ClinVar variant_summary.txt.gz header parsing stripped `#` from all column names, turning `RS# (dbSNP)` into `RS (dbSNP)`, so the rsid column lookup was always undefined — resulting in 0 matches from 8.6M lines+- **Solution**: Strip only the leading `#` from the header line (it's a comment prefix on `#AlleleID`) instead of from individual column names, preserving `RS# (dbSNP)` intact+### Codex CLI Provider — Wrong Argument Convention- **Fix**: The CLI runner hardcoded `-p -` (Claude's "print, read from stdin" flag) for all CLI providers, but Codex CLI interprets `-p` as `--profile`, causing `Error loading configuration: config profile '-' not found` and immediate exit code 1- **Solution**: Added `buildCliArgs()` function that constructs provider-specific arguments — Codex uses `exec --model <model> -` (stdin marker), Gemini uses bare args, and Claude retains `-p -`diff --git a/client/package.json b/client/package.jsonindex 18332cdd7d..6947a251a8 100644--- a/client/package.json+++ b/client/package.json@@ -17,6 +17,7 @@"@xterm/addon-fit": "^0.11.0","@xterm/addon-web-links": "^0.12.0","@xterm/xterm": "^6.0.0",+ "fflate": "^0.8.2","geist": "^1.7.0","lucide-react": "^0.562.0","react": "^18.3.1",diff --git a/client/src/components/digital-twin/GenomeCategoryCard.jsx b/client/src/components/digital-twin/GenomeCategoryCard.jsxnew file mode 100644index 0000000000..b04f0b5262--- /dev/null+++ b/client/src/components/digital-twin/GenomeCategoryCard.jsx@@ -0,0 +1,199 @@+import { useState } from 'react';+import { ChevronDown, ChevronRight } from 'lucide-react';++const STATUS_DOT = {+ beneficial: 'bg-green-400',+ typical: 'bg-blue-400',+ concern: 'bg-yellow-400',+ major_concern: 'bg-red-400',+ not_found: 'bg-gray-500'+};++const STATUS_LABEL = {+ beneficial: 'Beneficial',+ typical: 'Typical',+ concern: 'Concern',+ major_concern: 'Major Concern',+ not_found: 'Not Found'+};++const STATUS_BADGE = {+ beneficial: { bg: 'bg-green-500/20', text: 'text-green-400', border: 'border-green-500/30' },+ typical: { bg: 'bg-blue-500/20', text: 'text-blue-400', border: 'border-blue-500/30' },+ concern: { bg: 'bg-yellow-500/20', text: 'text-yellow-400', border: 'border-yellow-500/30' },+ major_concern: { bg: 'bg-red-500/20', text: 'text-red-400', border: 'border-red-500/30' },+ not_found: { bg: 'bg-gray-500/20', text: 'text-gray-400', border: 'border-gray-500/30' }+};++const COLOR_MAP = {+ purple: 'border-purple-500/30 bg-purple-500/5',+ rose: 'border-rose-500/30 bg-rose-500/5',+ red: 'border-red-500/30 bg-red-500/5',+ blue: 'border-blue-500/30 bg-blue-500/5',+ emerald: 'border-emerald-500/30 bg-emerald-500/5',+ amber: 'border-amber-500/30 bg-amber-500/5',+ green: 'border-green-500/30 bg-green-500/5',+ orange: 'border-orange-500/30 bg-orange-500/5',+ indigo: 'border-indigo-500/30 bg-indigo-500/5',+ cyan: 'border-cyan-500/30 bg-cyan-500/5',+ violet: 'border-violet-500/30 bg-violet-500/5',+ sky: 'border-sky-500/30 bg-sky-500/5',+ yellow: 'border-yellow-500/30 bg-yellow-500/5'+};++export default function GenomeCategoryCard({ category, label, emoji, color, markers, onEditNotes, onDeleteMarker }) {+ const [expanded, setExpanded] = useState(true);+ const [expandedMarker, setExpandedMarker] = useState(null);++ const statusSummary = markers.reduce((acc, m) => {+ acc[m.status] = (acc[m.status] || 0) + 1;+ return acc;+ }, {});++ const headerColor = COLOR_MAP[color] || COLOR_MAP.blue;++ return (+ <div className={`border rounded-lg ${headerColor}`}>+ {/* Category header */}+ <button+ onClick={() => setExpanded(!expanded)}+ className="w-full flex items-center justify-between px-3 py-2.5 text-left hover:bg-white/5 transition-colors rounded-t-lg"+ >+ <div className="flex items-center gap-2">+ <span className="text-lg leading-none">{emoji}</span>+ <span className="font-medium text-white text-sm">{label}</span>+ <span className="text-xs text-gray-500">({markers.length})</span>+ </div>+ <div className="flex items-center gap-3">+ <div className="flex gap-1.5 text-xs">+ {statusSummary.beneficial > 0 && <span className="text-green-400">{statusSummary.beneficial} good</span>}+ {statusSummary.concern > 0 && <span className="text-yellow-400">{statusSummary.concern} concern</span>}+ {statusSummary.major_concern > 0 && <span className="text-red-400">{statusSummary.major_concern} major</span>}+ </div>+ {expanded ? <ChevronDown size={14} className="text-gray-500" /> : <ChevronRight size={14} className="text-gray-500" />}+ </div>+ </button>++ {/* Marker grid */}+ {expanded && (+ <div className="border-t border-port-border/50 p-2">+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">+ {markers.map(marker => {+ const isExpanded = expandedMarker === marker.id;+ const badge = STATUS_BADGE[marker.status] || STATUS_BADGE.not_found;+ const dot = STATUS_DOT[marker.status] || STATUS_DOT.not_found;++ return (+ <div+ key={marker.id}+ className={`rounded-md border transition-colors ${+ isExpanded+ ? 'border-port-accent/40 bg-port-bg/60 col-span-1 sm:col-span-2 lg:col-span-3'+ : 'border-port-border/40 bg-port-card/50 hover:border-port-border'+ }`}+ >+ {/* Compact marker tile */}+ <button+ onClick={() => setExpandedMarker(isExpanded ? null : marker.id)}+ className="w-full p-2.5 text-left"+ >+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className={`w-2 h-2 rounded-full flex-shrink-0 ${dot}`} />+ <span className="text-xs font-medium text-white truncate">{marker.name}</span>+ </div>+ <div className="flex items-center gap-2 mt-1 ml-3.5">+ <span className="text-[10px] text-gray-500 font-mono">{marker.gene}</span>+ <span className="text-[10px] text-gray-600 font-mono">{marker.rsid}</span>+ </div>+ </div>+ {marker.genotype && (+ <span className="px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-[10px] font-mono text-white flex-shrink-0">+ {marker.genotype}+ </span>+ )}+ </div>+ </button>++ {/* Expanded detail panel */}+ {isExpanded && (+ <div className="px-3 pb-3 space-y-3 border-t border-port-border/30">+ {/* Status + genotype row */}+ <div className="flex items-center gap-2 pt-2 flex-wrap">+ <span className={`px-2 py-0.5 rounded text-xs font-medium ${badge.bg} ${badge.text} border ${badge.border}`}>+ {STATUS_LABEL[marker.status] || marker.status}+ </span>+ {marker.genotype && (+ <span className="px-2 py-0.5 rounded bg-port-card border border-port-border text-xs font-mono text-white">+ {marker.genotype}+ </span>+ )}+ <span className="text-xs text-gray-500 font-mono">{marker.gene} · {marker.rsid}</span>+ </div>++ {/* Description */}+ <p className="text-sm text-gray-400 leading-relaxed">{marker.description}</p>++ {/* Implications */}+ {marker.implications && (+ <div className="p-2 rounded bg-port-card border border-port-border">+ <span className="text-[10px] font-medium text-gray-500 uppercase tracking-wide">Implications</span>+ <p className="text-sm text-gray-300 mt-1">{marker.implications}</p>+ </div>+ )}++ {/* Location */}+ <div className="flex gap-4 text-xs text-gray-500">+ {marker.chromosome && <span>Chr {marker.chromosome}</span>}+ {marker.position && <span>Pos {marker.position}</span>}+ </div>++ {/* Notes */}+ <div>+ <label className="text-[10px] font-medium text-gray-500 uppercase tracking-wide">Notes</label>+ <textarea+ value={marker.notes || ''}+ onChange={(e) => onEditNotes(marker.id, e.target.value)}+ placeholder="Add personal notes..."+ rows={2}+ className="w-full mt-1 p-2 bg-port-card border border-port-border rounded text-sm text-white placeholder-gray-600 resize-none focus:outline-none focus:border-port-accent"+ />+ </div>++ {/* References */}+ {marker.references?.length > 0 && (+ <div>+ <span className="text-[10px] font-medium text-gray-500 uppercase tracking-wide">References</span>+ <ul className="mt-1 space-y-1">+ {marker.references.map((ref, i) => (+ <li key={i}>+ <a href={ref} target="_blank" rel="noopener noreferrer" className="text-xs text-port-accent hover:underline break-all">+ {ref}+ </a>+ </li>+ ))}+ </ul>+ </div>+ )}++ {/* Delete */}+ <div className="flex justify-end">+ <button+ onClick={(e) => { e.stopPropagation(); onDeleteMarker(marker.id); }}+ className="text-xs text-red-400 hover:text-red-300 transition-colors"+ >+ Remove marker+ </button>+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.jsindex 9b70cf7d88..a3401897c6 100644--- a/client/src/components/digital-twin/constants.js+++ b/client/src/components/digital-twin/constants.js@@ -23,7 +23,8 @@ import {GitBranch,AlertOctagon,Fingerprint,- Globe+ Globe,+ Dna} from 'lucide-react';// Main navigation tabs@@ -33,6 +34,7 @@ export const TABS = [{ id: 'test', label: 'Test', icon: CheckCircle },{ id: 'enrich', label: 'Enrich', icon: Sparkles },{ id: 'accounts', label: 'Accounts', icon: Globe },+ { id: 'genome', label: 'Genome', icon: Dna },{ id: 'interview', label: 'Interview', icon: MessageSquare },{ id: 'import', label: 'Import', icon: Upload },{ id: 'export', label: 'Export', icon: Download }diff --git a/client/src/components/digital-twin/tabs/GenomeTab.jsx b/client/src/components/digital-twin/tabs/GenomeTab.jsxnew file mode 100644index 0000000000..f6a52c7726--- /dev/null+++ b/client/src/components/digital-twin/tabs/GenomeTab.jsx@@ -0,0 +1,747 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import toast from 'react-hot-toast';+import {+ Upload, Download, RefreshCw, Trash2, Search, Dna, AlertTriangle, Save+} from 'lucide-react';+import { unzipSync, strFromU8 } from 'fflate';+import * as api from '../../../services/api';+import GenomeCategoryCard from '../GenomeCategoryCard';++const CATEGORY_META = {+ longevity: { emoji: '\u2728', label: 'Longevity', color: 'purple' },+ cardiovascular: { emoji: '\u2764\uFE0F', label: 'Cardiovascular', color: 'rose' },+ iron: { emoji: '\u{1FA78}', label: 'Iron Metabolism', color: 'red' },+ methylation: { emoji: '\u{1F52C}', label: 'Methylation', color: 'blue' },+ nutrient: { emoji: '\u{1F34E}', label: 'Nutrient Metabolism', color: 'emerald' },+ caffeine: { emoji: '\u2615', label: 'Caffeine', color: 'amber' },+ detox: { emoji: '\u{1F6E1}\uFE0F', label: 'Detoxification', color: 'green' },+ 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' },+ 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' }+};++const STAR_LABELS = ['No criteria', 'Single submitter', 'Multiple submitters', 'Expert panel', 'Practice guideline'];++const SEVERITY_LABELS = {+ pathogenic: { label: 'Pathogenic', bg: 'bg-red-500/20', text: 'text-red-400', border: 'border-red-500/30' },+ drug_response: { label: 'Drug Response', bg: 'bg-purple-500/20', text: 'text-purple-400', border: 'border-purple-500/30' },+ risk_factor: { label: 'Risk Factor', bg: 'bg-yellow-500/20', text: 'text-yellow-400', border: 'border-yellow-500/30' },+ protective: { label: 'Protective', bg: 'bg-green-500/20', text: 'text-green-400', border: 'border-green-500/30' }+};++export default function GenomeTab() {+ const [summary, setSummary] = useState(null);+ const [loading, setLoading] = useState(true);+ const [uploading, setUploading] = useState(false);+ const [scanning, setScanning] = useState(false);+ const [searching, setSearching] = useState(false);+ const [searchRsid, setSearchRsid] = useState('');+ const [searchResult, setSearchResult] = useState(null);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const [savingNotes, setSavingNotes] = useState(null);++ // ClinVar state+ const [clinvarStatus, setClinvarStatus] = useState(null);+ const [clinvarSyncing, setClinvarSyncing] = useState(false);+ const [clinvarProgress, setClinvarProgress] = useState('');+ const [clinvarResults, setClinvarResults] = useState(null);+ const [clinvarScanning, setClinvarScanning] = useState(false);+ const [clinvarExpanded, setClinvarExpanded] = useState({});+ const [clinvarFilter, setClinvarFilter] = useState('all');+ const [clinvarStarFilter, setClinvarStarFilter] = useState(0);+ const fileInputRef = useRef(null);+ const dropRef = useRef(null);+ const notesTimerRef = useRef({});++ const fetchSummary = useCallback(async () => {+ const [data, cvStatus] = await Promise.all([+ api.getGenomeSummary().catch(() => ({ uploaded: false })),+ api.getClinvarStatus().catch(() => ({ synced: false }))+ ]);+ setSummary(data);+ setClinvarStatus(cvStatus);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchSummary();+ }, [fetchSummary]);++ // Debounced notes save+ const handleNotesChange = useCallback((markerId, notes) => {+ // Optimistic UI update+ setSummary(prev => {+ if (!prev?.savedMarkers?.[markerId]) return prev;+ return {+ ...prev,+ savedMarkers: {+ ...prev.savedMarkers,+ [markerId]: { ...prev.savedMarkers[markerId], notes }+ }+ };+ });++ // Debounce the API call+ if (notesTimerRef.current[markerId]) {+ clearTimeout(notesTimerRef.current[markerId]);+ }+ notesTimerRef.current[markerId] = setTimeout(async () => {+ setSavingNotes(markerId);+ await api.updateGenomeMarkerNotes(markerId, notes).catch(() => {+ toast.error('Failed to save notes');+ });+ setSavingNotes(null);+ }, 800);+ }, []);++ const handleFileUpload = useCallback(async (file) => {+ if (!file) return;+ if (file.size > 50 * 1024 * 1024) {+ toast.error('File too large (max 50MB)');+ return;+ }++ setUploading(true);+ const isZip = file.name.endsWith('.zip') || file.type === 'application/zip';++ if (isZip) {+ // Read as ArrayBuffer, unzip, and extract the .txt file inside+ const reader = new FileReader();+ reader.onload = async (e) => {+ const zipData = new Uint8Array(e.target.result);+ const unzipped = unzipSync(zipData);+ const txtFile = Object.keys(unzipped).find(name => name.endsWith('.txt'));+ if (!txtFile) {+ toast.error('No .txt file found inside the zip');+ setUploading(false);+ return;+ }+ const content = strFromU8(unzipped[txtFile]);+ const result = await api.uploadGenomeFile(content, txtFile).catch(() => null);+ if (result) {+ toast.success(`Genome uploaded: ${result.snpCount.toLocaleString()} SNPs found`);+ await fetchSummary();+ }+ setUploading(false);+ };+ reader.readAsArrayBuffer(file);+ } else {+ // Read as text directly+ const reader = new FileReader();+ reader.onload = async (e) => {+ const content = e.target.result;+ const result = await api.uploadGenomeFile(content, file.name).catch(() => null);+ if (result) {+ toast.success(`Genome uploaded: ${result.snpCount.toLocaleString()} SNPs found`);+ await fetchSummary();+ }+ setUploading(false);+ };+ reader.readAsText(file);+ }+ }, [fetchSummary]);++ const handleDrop = useCallback((e) => {+ e.preventDefault();+ e.stopPropagation();+ dropRef.current?.classList.remove('border-port-accent');+ const file = e.dataTransfer.files[0];+ if (file) handleFileUpload(file);+ }, [handleFileUpload]);++ const handleDragOver = useCallback((e) => {+ e.preventDefault();+ e.stopPropagation();+ dropRef.current?.classList.add('border-port-accent');+ }, []);++ const handleDragLeave = useCallback((e) => {+ e.preventDefault();+ e.stopPropagation();+ dropRef.current?.classList.remove('border-port-accent');+ }, []);++ const handleScan = useCallback(async () => {+ setScanning(true);+ const result = await api.scanGenomeMarkers().catch(() => null);+ if (result) {+ toast.success(`Scanned ${result.markers.length} curated markers`);+ await fetchSummary();+ }+ setScanning(false);+ }, [fetchSummary]);++ const handleSearch = useCallback(async () => {+ if (!searchRsid || !/^rs\d+$/.test(searchRsid)) {+ toast.error('Enter a valid rsid (e.g., rs1801133)');+ return;+ }+ setSearching(true);+ setSearchResult(null);+ const result = await api.searchGenomeSNP(searchRsid).catch(() => null);+ setSearchResult(result);+ setSearching(false);+ }, [searchRsid]);++ const handleSaveSearchResult = useCallback(async () => {+ if (!searchResult?.found) return;+ const data = {+ rsid: searchResult.rsid,+ genotype: searchResult.genotype,+ chromosome: searchResult.chromosome,+ position: searchResult.position,+ name: searchResult.name || searchResult.rsid,+ category: searchResult.category || 'other',+ gene: searchResult.gene || '',+ description: searchResult.description || '',+ implications: searchResult.implications || '',+ status: searchResult.status || 'typical'+ };+ const saved = await api.saveGenomeMarker(data).catch(() => null);+ if (saved) {+ toast.success(`Marker ${searchResult.rsid} saved`);+ await fetchSummary();+ }+ }, [searchResult, fetchSummary]);++ const handleDeleteMarker = useCallback(async (markerId) => {+ await api.deleteGenomeMarker(markerId).catch(() => null);+ toast.success('Marker removed');+ await fetchSummary();+ }, [fetchSummary]);++ const handleDeleteGenome = useCallback(async () => {+ setDeleting(true);+ await api.deleteGenomeData().catch(() => null);+ toast.success('Genome data deleted');+ setConfirmDelete(false);+ setDeleting(false);+ setSummary({ uploaded: false });+ setClinvarResults(null);+ }, []);++ // ClinVar handlers+ const handleClinvarSync = useCallback(async () => {+ setClinvarSyncing(true);+ setClinvarProgress('Starting ClinVar sync...');+ const result = await api.syncClinvar().catch((err) => {+ setClinvarProgress('');+ return null;+ });+ if (result) {+ toast.success(`ClinVar synced: ${result.variantCount?.toLocaleString()} variants indexed`);+ setClinvarStatus(result);+ }+ setClinvarSyncing(false);+ setClinvarProgress('');+ }, []);++ const handleClinvarScan = useCallback(async () => {+ setClinvarScanning(true);+ const result = await api.scanClinvar().catch(() => null);+ if (result) {+ setClinvarResults(result);+ toast.success(`ClinVar scan: ${result.totalMatched} variants found in your genome`);+ }+ setClinvarScanning(false);+ }, []);+++ if (loading) {+ return (+ <div className="flex items-center justify-center py-20">+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />+ </div>+ );+ }++ // Upload state — no genome data yet+ if (!summary?.uploaded) {+ return (+ <div className="max-w-2xl mx-auto space-y-6">+ <div className="text-center space-y-2">+ <Dna className="w-12 h-12 text-purple-400 mx-auto" />+ <h2 className="text-xl font-bold text-white">Genome Data</h2>+ <p className="text-gray-400">Upload your 23andMe raw data export to track health and longevity markers.</p>+ </div>++ {/* Drop zone */}+ <div+ ref={dropRef}+ onDrop={handleDrop}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ className="border-2 border-dashed border-port-border rounded-lg p-12 text-center transition-colors hover:border-gray-500 cursor-pointer"+ onClick={() => fileInputRef.current?.click()}+ >+ {uploading ? (+ <div className="space-y-3">+ <RefreshCw className="w-10 h-10 text-port-accent animate-spin mx-auto" />+ <p className="text-gray-400">Parsing genome data...</p>+ </div>+ ) : (+ <div className="space-y-3">+ <Upload className="w-10 h-10 text-gray-500 mx-auto" />+ <p className="text-gray-300">Drag and drop your 23andMe raw data file</p>+ <p className="text-sm text-gray-500">or click to browse</p>+ <p className="text-xs text-gray-600">Accepts .zip or .txt files from 23andMe (typically 15-25MB)</p>+ </div>+ )}+ <input+ ref={fileInputRef}+ type="file"+ accept=".txt,.tsv,.csv,.zip"+ className="hidden"+ onChange={(e) => handleFileUpload(e.target.files[0])}+ />+ </div>++ <div className="p-3 rounded bg-port-card border border-port-border text-sm text-gray-400">+ <p className="flex items-start gap-2">+ <AlertTriangle size={16} className="text-yellow-500 mt-0.5 flex-shrink-0" />+ <span>+ Your genome data is stored locally on this server only. It is never sent to external services.+ All analysis is performed locally using a curated list of known health markers.+ </span>+ </p>+ </div>+ </div>+ );+ }++ // Loaded state — genome data exists+ const markers = summary.savedMarkers ? Object.entries(summary.savedMarkers).map(([id, m]) => ({ id, ...m })) : [];++ // Group markers by category+ const grouped = {};+ for (const marker of markers) {+ const cat = marker.category || 'other';+ if (!grouped[cat]) grouped[cat] = [];+ grouped[cat].push(marker);+ }++ // Sort categories by a defined order+ const categoryOrder = ['longevity', 'cardiovascular', 'tumor_suppression', '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);+ return (ai === -1 ? 99 : ai) - (bi === -1 ? 99 : bi);+ });++ return (+ <div className="space-y-6">+ {/* Stats bar */}+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">+ <StatCard label="SNPs" value={summary.snpCount?.toLocaleString()} />+ <StatCard label="Build" value={summary.build} />+ <StatCard label="Markers" value={summary.markerCount || 0} />+ <StatCard label="Uploaded" value={summary.uploadedAt ? new Date(summary.uploadedAt).toLocaleDateString() : 'N/A'} />+ </div>++ {/* Status summary */}+ {summary.statusCounts && (+ <div className="flex flex-wrap gap-2 text-sm">+ {summary.statusCounts.beneficial > 0 && (+ <span className="px-2 py-1 rounded bg-green-500/10 text-green-400 border border-green-500/20">+ {summary.statusCounts.beneficial} beneficial+ </span>+ )}+ {summary.statusCounts.typical > 0 && (+ <span className="px-2 py-1 rounded bg-blue-500/10 text-blue-400 border border-blue-500/20">+ {summary.statusCounts.typical} typical+ </span>+ )}+ {summary.statusCounts.concern > 0 && (+ <span className="px-2 py-1 rounded bg-yellow-500/10 text-yellow-400 border border-yellow-500/20">+ {summary.statusCounts.concern} concern+ </span>+ )}+ {summary.statusCounts.major_concern > 0 && (+ <span className="px-2 py-1 rounded bg-red-500/10 text-red-400 border border-red-500/20">+ {summary.statusCounts.major_concern} major concern+ </span>+ )}+ {summary.statusCounts.not_found > 0 && (+ <span className="px-2 py-1 rounded bg-gray-500/10 text-gray-400 border border-gray-500/20">+ {summary.statusCounts.not_found} not found+ </span>+ )}+ </div>+ )}++ {/* Actions row */}+ <div className="flex flex-wrap gap-2">+ <button+ onClick={handleScan}+ disabled={scanning}+ className="flex items-center gap-2 px-3 py-2 bg-port-accent/20 text-port-accent border border-port-accent/30 rounded hover:bg-port-accent/30 transition-colors disabled:opacity-50 text-sm"+ >+ {scanning ? <RefreshCw size={14} className="animate-spin" /> : <Dna size={14} />}+ {scanning ? 'Scanning...' : 'Scan Known Markers'}+ </button>+ <button+ onClick={() => setConfirmDelete(true)}+ className="flex items-center gap-2 px-3 py-2 bg-red-500/10 text-red-400 border border-red-500/20 rounded hover:bg-red-500/20 transition-colors text-sm"+ >+ <Trash2 size={14} />+ Delete Genome+ </button>+ </div>++ {/* Delete confirmation */}+ {confirmDelete && (+ <div className="p-4 rounded bg-red-500/10 border border-red-500/30 space-y-3">+ <p className="text-sm text-red-400 font-medium">+ Are you sure? This will permanently delete your raw genome file and all saved markers.+ </p>+ <div className="flex gap-2">+ <button+ onClick={handleDeleteGenome}+ disabled={deleting}+ className="px-3 py-1.5 bg-red-500/20 text-red-400 border border-red-500/30 rounded text-sm hover:bg-red-500/30 disabled:opacity-50"+ >+ {deleting ? 'Deleting...' : 'Yes, delete everything'}+ </button>+ <button+ onClick={() => setConfirmDelete(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>+ )}++ {/* Curated Markers by category */}+ {sortedCategories.length > 0 && (+ <div className="space-y-4">+ <h3 className="text-lg font-semibold text-white">Curated Markers</h3>+ {sortedCategories.map(cat => {+ const meta = CATEGORY_META[cat] || { emoji: '\u{1F9EC}', label: cat, color: 'blue' };+ return (+ <GenomeCategoryCard+ key={cat}+ category={cat}+ label={meta.label}+ emoji={meta.emoji}+ color={meta.color}+ markers={grouped[cat]}+ onEditNotes={handleNotesChange}+ onDeleteMarker={handleDeleteMarker}+ />+ );+ })}+ </div>+ )}++ {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>+ </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">+ <div>+ <h3 className="text-lg font-semibold text-white">ClinVar Database</h3>+ <p className="text-xs text-gray-500 mt-0.5">+ NCBI's database of clinically significant genetic variants — pathogenic mutations, risk factors, drug responses, and protective variants.+ </p>+ </div>+ </div>++ {/* ClinVar status + actions */}+ <div className="flex flex-wrap items-center gap-2">+ {!clinvarStatus?.synced ? (+ <button+ onClick={handleClinvarSync}+ disabled={clinvarSyncing}+ className="flex items-center gap-2 px-3 py-2 bg-purple-500/20 text-purple-400 border border-purple-500/30 rounded hover:bg-purple-500/30 transition-colors disabled:opacity-50 text-sm"+ >+ {clinvarSyncing ? <RefreshCw size={14} className="animate-spin" /> : <Download size={14} />}+ {clinvarSyncing ? 'Syncing...' : 'Sync ClinVar Database'}+ </button>+ ) : (+ <>+ <span className="text-xs text-gray-500">+ {clinvarStatus.variantCount?.toLocaleString()} variants indexed+ {clinvarStatus.syncedAt && ` (synced ${new Date(clinvarStatus.syncedAt).toLocaleDateString()})`}+ </span>+ <button+ onClick={handleClinvarScan}+ disabled={clinvarScanning}+ className="flex items-center gap-2 px-3 py-2 bg-purple-500/20 text-purple-400 border border-purple-500/30 rounded hover:bg-purple-500/30 transition-colors disabled:opacity-50 text-sm"+ >+ {clinvarScanning ? <RefreshCw size={14} className="animate-spin" /> : <Search size={14} />}+ {clinvarScanning ? 'Scanning...' : 'Scan Against ClinVar'}+ </button>+ <button+ onClick={handleClinvarSync}+ disabled={clinvarSyncing}+ className="px-3 py-2 bg-port-card border border-port-border rounded text-xs text-gray-500 hover:text-white transition-colors disabled:opacity-50"+ >+ {clinvarSyncing ? 'Re-syncing...' : 'Re-sync'}+ </button>+ </>+ )}+ </div>++ {/* Sync progress */}+ {clinvarProgress && (+ <div className="flex items-center gap-2 p-3 rounded bg-purple-500/10 border border-purple-500/20 text-sm text-purple-300">+ <RefreshCw size={14} className="animate-spin flex-shrink-0" />+ {clinvarProgress}+ </div>+ )}++ {/* ClinVar scan results */}+ {clinvarResults && (+ <div className="space-y-3">+ {/* Summary badges */}+ <div className="flex flex-wrap gap-2 text-sm">+ <span className="px-2 py-1 rounded bg-port-card border border-port-border text-gray-300">+ {clinvarResults.totalMatched} total matches+ </span>+ {clinvarResults.bySeverity.pathogenic > 0 && (+ <span className="px-2 py-1 rounded bg-red-500/10 text-red-400 border border-red-500/20">+ {clinvarResults.bySeverity.pathogenic} pathogenic+ </span>+ )}+ {clinvarResults.bySeverity.risk_factor > 0 && (+ <span className="px-2 py-1 rounded bg-yellow-500/10 text-yellow-400 border border-yellow-500/20">+ {clinvarResults.bySeverity.risk_factor} risk factors+ </span>+ )}+ {clinvarResults.bySeverity.drug_response > 0 && (+ <span className="px-2 py-1 rounded bg-purple-500/10 text-purple-400 border border-purple-500/20">+ {clinvarResults.bySeverity.drug_response} drug response+ </span>+ )}+ {clinvarResults.bySeverity.protective > 0 && (+ <span className="px-2 py-1 rounded bg-green-500/10 text-green-400 border border-green-500/20">+ {clinvarResults.bySeverity.protective} protective+ </span>+ )}+ </div>++ {/* Filters */}+ <div className="flex flex-wrap gap-2">+ <div className="flex gap-1 text-xs">+ {['all', 'pathogenic', 'risk_factor', 'drug_response', 'protective'].map(f => (+ <button+ key={f}+ onClick={() => setClinvarFilter(f)}+ className={`px-2 py-1 rounded border transition-colors ${+ clinvarFilter === f+ ? 'bg-port-accent/20 text-port-accent border-port-accent/30'+ : 'bg-port-card border-port-border text-gray-500 hover:text-white'+ }`}+ >+ {f === 'all' ? 'All' : (SEVERITY_LABELS[f]?.label || f)}+ </button>+ ))}+ </div>+ <select+ value={clinvarStarFilter}+ onChange={(e) => setClinvarStarFilter(Number(e.target.value))}+ className="px-2 py-1 rounded bg-port-card border border-port-border text-xs text-gray-400 focus:outline-none"+ >+ <option value={0}>Any evidence</option>+ <option value={1}>1+ star</option>+ <option value={2}>2+ stars</option>+ <option value={3}>3+ stars (expert panel)</option>+ </select>+ </div>++ {/* Findings list */}+ <div className="border rounded-lg border-port-border overflow-hidden">+ <div className="max-h-[600px] overflow-auto">+ {clinvarResults.findings+ .filter(f => clinvarFilter === 'all' || f.severity === clinvarFilter)+ .filter(f => f.reviewStars >= clinvarStarFilter)+ .slice(0, 200)+ .map((finding, i) => {+ const sev = SEVERITY_LABELS[finding.severity] || SEVERITY_LABELS.risk_factor;+ const isOpen = clinvarExpanded[`cv-${i}`];+ return (+ <div key={`${finding.rsid}-${i}`} className="border-b border-port-border/50 last:border-b-0">+ <button+ onClick={() => setClinvarExpanded(prev => ({ ...prev, [`cv-${i}`]: !prev[`cv-${i}`] }))}+ className="w-full flex items-center justify-between p-2.5 text-left hover:bg-white/5 transition-colors text-sm"+ >+ <div className="flex items-center gap-2 flex-1 min-w-0">+ <span className="font-mono text-xs text-gray-500 w-24 flex-shrink-0">{finding.rsid}</span>+ <span className="text-white font-medium truncate">{finding.gene}</span>+ <span className={`px-1.5 py-0.5 rounded text-xs ${sev.bg} ${sev.text} border ${sev.border} flex-shrink-0`}>+ {sev.label}+ </span>+ </div>+ <div className="flex items-center gap-2 flex-shrink-0 ml-2">+ <span className="text-xs text-yellow-500" title={STAR_LABELS[finding.reviewStars] || ''}>+ {'★'.repeat(finding.reviewStars)}{'☆'.repeat(4 - finding.reviewStars)}+ </span>+ </div>+ </button>+ {isOpen && (+ <div className="px-3 pb-3 space-y-2 bg-port-bg/30 text-sm">+ <div className="flex gap-4 text-xs text-gray-500">+ <span>Chr {finding.chromosome}</span>+ <span>Pos {finding.position}</span>+ <span className="font-mono">{finding.genotype}</span>+ <span>{finding.submissions} submission{finding.submissions > 1 ? 's' : ''}</span>+ </div>+ <div className="text-xs text-gray-400">+ <span className="font-medium text-gray-500">Classification: </span>+ {finding.significance}+ </div>+ {finding.conditions.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {finding.conditions.map((c, j) => (+ <span key={j} className="px-1.5 py-0.5 rounded bg-port-card border border-port-border text-xs text-gray-300">+ {c}+ </span>+ ))}+ </div>+ )}+ <div className="text-xs text-gray-500">+ Review: {STAR_LABELS[finding.reviewStars] || 'No criteria provided'}+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>+ {clinvarResults.findings+ .filter(f => clinvarFilter === 'all' || f.severity === clinvarFilter)+ .filter(f => f.reviewStars >= clinvarStarFilter)+ .length > 200 && (+ <div className="p-2 text-center text-xs text-gray-500 border-t border-port-border bg-port-card">+ Showing first 200 of {clinvarResults.findings.filter(f => clinvarFilter === 'all' || f.severity === clinvarFilter).filter(f => f.reviewStars >= clinvarStarFilter).length} results. Use filters to narrow.+ </div>+ )}+ </div>++ <p className="text-xs text-gray-600">+ Data from NCBI ClinVar. For research/informational purposes only — consult a genetic counselor for clinical interpretation.+ </p>+ </div>+ )}+ </div>++ {/* Search section */}+ <div className="border-t border-port-border pt-6 space-y-4">+ <h3 className="text-lg font-semibold text-white">Search SNP</h3>+ <div className="flex gap-2">+ <input+ type="text"+ value={searchRsid}+ onChange={(e) => setSearchRsid(e.target.value.toLowerCase().trim())}+ onKeyDown={(e) => e.key === 'Enter' && handleSearch()}+ placeholder="rs1801133"+ className="flex-1 max-w-xs px-3 py-2 bg-port-card border border-port-border rounded text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent font-mono"+ />+ <button+ onClick={handleSearch}+ disabled={searching}+ className="flex items-center gap-2 px-3 py-2 bg-port-card border border-port-border rounded text-sm text-gray-300 hover:text-white hover:border-port-accent transition-colors disabled:opacity-50"+ >+ {searching ? <RefreshCw size={14} className="animate-spin" /> : <Search size={14} />}+ Search+ </button>+ </div>++ {/* Search result */}+ {searchResult && (+ <div className="p-4 rounded bg-port-card border border-port-border space-y-3">+ {searchResult.found ? (+ <>+ <div className="flex items-center justify-between flex-wrap gap-2">+ <div className="flex items-center gap-2">+ <span className="font-mono text-white">{searchResult.rsid}</span>+ {searchResult.gene && <span className="text-sm text-gray-500">{searchResult.gene}</span>}+ <span className="px-2 py-0.5 rounded bg-port-bg border border-port-border text-xs font-mono text-white">+ {searchResult.genotype}+ </span>+ </div>+ {searchResult.status && (+ <StatusBadgeInline status={searchResult.status} />+ )}+ </div>+ <div className="text-xs text-gray-500 flex gap-4">+ <span>Chr {searchResult.chromosome}</span>+ <span>Pos {searchResult.position}</span>+ {searchResult.curated && <span className="text-purple-400">Curated marker</span>}+ </div>+ {searchResult.description && (+ <p className="text-sm text-gray-400">{searchResult.description}</p>+ )}+ {searchResult.implications && (+ <p className="text-sm text-gray-300">{searchResult.implications}</p>+ )}+ {searchResult.curated && (+ <button+ onClick={handleSaveSearchResult}+ className="flex items-center gap-1.5 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 transition-colors"+ >+ <Save size={14} />+ Save Marker+ </button>+ )}+ </>+ ) : (+ <p className="text-sm text-gray-500">+ SNP <span className="font-mono text-white">{searchResult.rsid || searchRsid}</span> not found in your genome data.+ </p>+ )}+ </div>+ )}+ </div>++ {/* Saving indicator */}+ {savingNotes && (+ <div className="fixed bottom-4 right-4 px-3 py-2 bg-port-card border border-port-border rounded shadow-lg text-xs text-gray-400 flex items-center gap-2">+ <RefreshCw size={12} className="animate-spin" />+ Saving notes...+ </div>+ )}+ </div>+ );+}++function StatCard({ label, value }) {+ return (+ <div className="p-3 rounded bg-port-card border border-port-border">+ <div className="text-xs text-gray-500 uppercase">{label}</div>+ <div className="text-lg font-bold text-white mt-1">{value}</div>+ </div>+ );+}++function StatusBadgeInline({ status }) {+ const styles = {+ beneficial: 'bg-green-500/20 text-green-400 border-green-500/30',+ typical: 'bg-blue-500/20 text-blue-400 border-blue-500/30',+ concern: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',+ major_concern: 'bg-red-500/20 text-red-400 border-red-500/30',+ not_found: 'bg-gray-500/20 text-gray-400 border-gray-500/30'+ };+ const labels = {+ beneficial: 'Beneficial',+ typical: 'Typical',+ concern: 'Concern',+ major_concern: 'Major Concern',+ not_found: 'Not Found'+ };+ return (+ <span className={`px-2 py-0.5 rounded text-xs font-medium border ${styles[status] || styles.not_found}`}>+ {labels[status] || status}+ </span>+ );+}diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsxindex fd1a14b737..e19d5351ef 100644--- a/client/src/pages/DigitalTwin.jsx+++ b/client/src/pages/DigitalTwin.jsx@@ -11,6 +11,7 @@ import TestTab from '../components/digital-twin/tabs/TestTab';import EnrichTab from '../components/digital-twin/tabs/EnrichTab';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 ImportTab from '../components/digital-twin/tabs/ImportTab';import ExportTab from '../components/digital-twin/tabs/ExportTab';@@ -55,6 +56,8 @@ export default function DigitalTwin() {return <EnrichTab onRefresh={fetchData} />;case 'accounts':return <AccountsTab />;+ case 'genome':+ return <GenomeTab />;case 'interview':return <InterviewTab onRefresh={fetchData} />;case 'import':diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 14acb57132..21decd5d12 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -974,6 +974,34 @@ export const deleteSocialAccount = (id) => request(`/digital-twin/social-accountmethod: 'DELETE'});+// Digital Twin - Genome+export const getGenomeSummary = () => request('/digital-twin/genome');+export const uploadGenomeFile = (content, filename) => request('/digital-twin/genome/upload', {+ method: 'POST',+ body: JSON.stringify({ content, filename })+});+export const scanGenomeMarkers = () => request('/digital-twin/genome/scan', { method: 'POST' });+export const searchGenomeSNP = (rsid) => request('/digital-twin/genome/search', {+ method: 'POST',+ body: JSON.stringify({ rsid })+});+export const saveGenomeMarker = (data) => request('/digital-twin/genome/markers', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateGenomeMarkerNotes = (id, notes) => request(`/digital-twin/genome/markers/${id}/notes`, {+ method: 'PUT',+ body: JSON.stringify({ notes })+});+export const deleteGenomeMarker = (id) => request(`/digital-twin/genome/markers/${id}`, { method: 'DELETE' });+export const deleteGenomeData = () => request('/digital-twin/genome', { method: 'DELETE' });++// Digital Twin - Genome ClinVar+export const getClinvarStatus = () => request('/digital-twin/genome/clinvar/status');+export const syncClinvar = () => request('/digital-twin/genome/clinvar/sync', { method: 'POST' });+export const scanClinvar = () => request('/digital-twin/genome/clinvar/scan', { method: 'POST' });+export const deleteClinvar = () => request('/digital-twin/genome/clinvar', { method: 'DELETE' });+// Browser - CDP browser managementexport const getBrowserStatus = () => request('/browser');export const getBrowserConfig = () => request('/browser/config');diff --git a/package-lock.json b/package-lock.jsonindex 2256660541..3452bf71a8 100644--- a/package-lock.json+++ b/package-lock.json@@ -39,6 +39,7 @@"@xterm/addon-fit": "^0.11.0","@xterm/addon-web-links": "^0.12.0","@xterm/xterm": "^6.0.0",+ "fflate": "^0.8.2","geist": "^1.7.0","lucide-react": "^0.562.0","react": "^18.3.1",@@ -101,6 +102,7 @@"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.27.1","@babel/generator": "^7.28.5",@@ -394,6 +396,7 @@"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz","integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==","license": "MIT",+ "peer": true,"dependencies": {"@dnd-kit/accessibility": "^3.1.1","@dnd-kit/utilities": "^3.2.2",@@ -436,7 +439,6 @@"integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==","license": "MIT","optional": true,- "peer": true,"dependencies": {"tslib": "^2.4.0"}@@ -889,7 +891,6 @@"integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==","license": "MIT","optional": true,- "peer": true,"engines": {"node": ">=18"}@@ -906,7 +907,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -929,7 +929,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -952,7 +951,6 @@"os": ["darwin"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -969,7 +967,6 @@"os": ["darwin"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -986,7 +983,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1003,7 +999,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1020,7 +1015,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1037,7 +1031,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1054,7 +1047,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1071,7 +1063,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1088,7 +1079,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1105,7 +1095,6 @@"os": ["linux"],- "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1122,7 +1111,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1145,7 +1133,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1168,7 +1155,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1191,7 +1177,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1214,7 +1199,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1237,7 +1221,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1260,7 +1243,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1283,7 +1265,6 @@"os": ["linux"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1303,7 +1284,6 @@],"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT","optional": true,- "peer": true,"dependencies": {"@emnapi/runtime": "^1.7.0"},@@ -1326,7 +1306,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1346,7 +1325,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1366,7 +1344,6 @@"os": ["win32"],- "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1446,8 +1423,7 @@"version": "16.1.6","resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.6.tgz","integrity": "sha512-N1ySLuZjnAtN3kFnwhAwPvZah8RJxKasD7x1f8shFqhncnWZn4JMfg37diLNuoHsLAlrDfM3g4mawVdtAG8XLQ==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@next/swc-darwin-arm64": {"version": "16.1.6",@@ -1461,7 +1437,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 10"}@@ -1478,7 +1453,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">= 10"}@@ -1495,7 +1469,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1512,7 +1485,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1529,7 +1501,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1546,7 +1517,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">= 10"}@@ -1563,7 +1533,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 10"}@@ -1580,7 +1549,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">= 10"}@@ -2042,6 +2010,7 @@"resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.18.0.tgz","integrity": "sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==","license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.17.8","@types/react-reconciler": "^0.26.7",@@ -2487,7 +2456,6 @@"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz","integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==","license": "Apache-2.0",- "peer": true,"dependencies": {"tslib": "^2.8.0"}@@ -2635,6 +2603,7 @@"resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.6.tgz","integrity": "sha512-NNu0sjyNxpoiW3YuVFfNz7mxSQ+S4X2G28uqg2s+CzoqoQjLPsWSbsFFyztIAqt2vb8kfEAsJNepMGPTxFDx3Q==","license": "MIT",+ "peer": true,"dependencies": {"undici-types": "~7.16.0"}@@ -2650,6 +2619,7 @@"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.13.tgz","integrity": "sha512-KkiJeU6VbYbUOp5ITMIc7kBfqlYkKA5KhEHVrGMmUUMt7NeaZg65ojdPk+FtNrBAOXNVM5QM72jnADjM+XVRAQ==","license": "MIT",+ "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -2674,6 +2644,7 @@"resolved": "https://registry.npmjs.org/@types/three/-/three-0.182.0.tgz","integrity": "sha512-WByN9V3Sbwbe2OkWuSGyoqQO8Du6yhYaXtXLoA5FkKTUJorZ+yOHBZ35zUUPQXlAKABZmbYp5oAqpA4RBjtJ/Q==","license": "MIT",+ "peer": true,"dependencies": {"@dimforge/rapier3d-compat": "~0.12.0","@tweenjs/tween.js": "~23.1.3",@@ -3281,6 +3252,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -3562,8 +3534,7 @@"version": "0.0.1","resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz","integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/cliui": {"version": "8.0.1",@@ -3787,7 +3758,8 @@"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/culvert": {"version": "0.1.2",@@ -3924,7 +3896,6 @@"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==","license": "Apache-2.0","optional": true,- "peer": true,"engines": {"node": ">=8"}@@ -4380,6 +4351,7 @@"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz","integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "^2.0.0","body-parser": "^2.2.1",@@ -5247,6 +5219,7 @@"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==","dev": true,"license": "MIT",+ "peer": true,"bin": {"jiti": "bin/jiti.js"}@@ -6292,7 +6265,6 @@"resolved": "https://registry.npmjs.org/next/-/next-16.1.6.tgz","integrity": "sha512-hkyRkcu5x/41KoqnROkfTm2pZVbKxvbZRuNvKXLRXxs3VfyO0WhY50TQS40EuKO9SW3rBj/sF3WbVwDACeMZyw==","license": "MIT",- "peer": true,"dependencies": {"@next/env": "16.1.6","@swc/helpers": "0.5.15",@@ -6360,7 +6332,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"nanoid": "^3.3.6","picocolors": "^1.0.0",@@ -6839,6 +6810,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -7148,6 +7120,7 @@"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -7172,6 +7145,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"@@ -7695,7 +7669,6 @@"hasInstallScript": true,"license": "Apache-2.0","optional": true,- "peer": true,"dependencies": {"@img/colour": "^1.0.0","detect-libc": "^2.1.2",@@ -7740,7 +7713,6 @@"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==","license": "ISC","optional": true,- "peer": true,"bin": {"semver": "bin/semver.js"},@@ -8195,7 +8167,6 @@"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz","integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==","license": "MIT",- "peer": true,"dependencies": {"client-only": "0.0.1"},@@ -8425,7 +8396,8 @@"version": "0.182.0","resolved": "https://registry.npmjs.org/three/-/three-0.182.0.tgz","integrity": "sha512-GbHabT+Irv+ihI1/f5kIIsZ+Ef9Sl5A1Y7imvS5RQjWgtTPfPnZ43JmlYI7NtCRDK9zir20lQpfg8/9Yd02OvQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/three-mesh-bvh": {"version": "0.7.8",@@ -8518,6 +8490,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -8931,6 +8904,7 @@"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.25.0","fdir": "^6.4.4",@@ -9024,6 +8998,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -9037,6 +9012,7 @@"integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@vitest/expect": "4.0.16","@vitest/mocker": "4.0.16",diff --git a/server/index.js b/server/index.jsindex 9f4831edaf..24964c95a2 100644--- a/server/index.js+++ b/server/index.js@@ -31,6 +31,7 @@ import notificationsRoutes from './routes/notifications.js';import standardizeRoutes from './routes/standardize.js';import brainRoutes from './routes/brain.js';import mediaRoutes from './routes/media.js';+import genomeRoutes from './routes/genome.js';import digitalTwinRoutes from './routes/digital-twin.js';import socialAccountsRoutes from './routes/socialAccounts.js';import lmstudioRoutes from './routes/lmstudio.js';@@ -194,6 +195,7 @@ app.use('/api/standardize', standardizeRoutes);app.use('/api/brain', brainRoutes);app.use('/api/media', mediaRoutes);app.use('/api/digital-twin/social-accounts', socialAccountsRoutes);+app.use('/api/digital-twin/genome', genomeRoutes);app.use('/api/digital-twin', digitalTwinRoutes);app.use('/api/lmstudio', lmstudioRoutes);app.use('/api/browser', browserRoutes);diff --git a/server/lib/curatedGenomeMarkers.js b/server/lib/curatedGenomeMarkers.jsnew file mode 100644index 0000000000..04fdc84159--- /dev/null+++ b/server/lib/curatedGenomeMarkers.js@@ -0,0 +1,670 @@+/**+ * Curated SNP database with classification logic for known health/longevity markers.+ * Each marker includes rsid, gene info, category, description, and genotype → status rules.+ */++export const MARKER_CATEGORIES = {+ longevity: { label: 'Longevity', icon: 'Sparkles', color: 'purple' },+ cardiovascular: { label: 'Cardiovascular', icon: 'HeartPulse', color: 'rose' },+ iron: { label: 'Iron Metabolism', icon: 'Droplet', color: 'red' },+ methylation: { label: 'Methylation', icon: 'Zap', color: 'blue' },+ nutrient: { label: 'Nutrient Metabolism', icon: 'Apple', color: 'emerald' },+ caffeine: { label: 'Caffeine', icon: 'Coffee', color: 'amber' },+ detox: { label: 'Detoxification', icon: 'Shield', color: 'green' },+ inflammation: { label: 'Inflammation', icon: 'Flame', color: 'orange' },+ tumor_suppression: { label: 'Tumor Suppression', icon: 'ShieldCheck', color: 'indigo' },+ cognitive: { label: 'Cognitive', icon: 'Brain', color: 'cyan' },+ 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' }+};++/**+ * Curated markers array. Each entry defines:+ * - rsid: The SNP identifier+ * - gene: Gene name+ * - name: Human-readable marker name+ * - category: One of MARKER_CATEGORIES keys+ * - description: What this marker relates to+ * - implications: Map of status → text explaining what that status means+ * - rules: Array of { genotypes: [...], status } for classification+ */+export const CURATED_MARKERS = [+ // === LONGEVITY ===+ {+ rsid: 'rs2802292',+ gene: 'FOXO3A',+ name: 'Longevity / FOXO3A',+ category: 'longevity',+ description: 'FOXO3A is one of the most replicated longevity-associated genes. The G allele is linked to exceptional lifespan across multiple populations.',+ implications: {+ beneficial: 'Carries the longevity-associated G/G genotype. Associated with improved stress resistance and cellular maintenance.',+ typical: 'Heterozygous carrier. Partial longevity association.',+ concern: 'Does not carry the longevity-associated allele.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['G/T', 'T/G'], status: 'typical' },+ { genotypes: ['T/T'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs2229765',+ gene: 'IGF1R',+ name: 'Insulin-like Growth Factor Receptor',+ category: 'longevity',+ description: 'IGF1R variants affect growth factor signaling. Reduced IGF-1 signaling is associated with extended lifespan in model organisms and centenarian studies.',+ implications: {+ beneficial: 'Genotype associated with favorable IGF-1 signaling for longevity.',+ typical: 'Intermediate IGF-1 receptor activity.',+ concern: 'Standard IGF-1 signaling — no longevity advantage from this variant.'+ },+ rules: [+ { genotypes: ['A/A'], status: 'beneficial' },+ { genotypes: ['A/G', 'G/A'], status: 'typical' },+ { genotypes: ['G/G'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs5882',+ gene: 'CETP',+ name: 'HDL Cholesterol / CETP',+ category: 'longevity',+ description: 'CETP transfers cholesterol between lipoproteins. The Val (G) allele is associated with higher HDL levels and longevity in Ashkenazi centenarian studies.',+ implications: {+ beneficial: 'Val/Val genotype — associated with higher HDL cholesterol and longevity.',+ typical: 'Heterozygous — intermediate HDL effect.',+ concern: 'Ile/Ile genotype — standard CETP activity.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['A/G', 'G/A'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs12366',+ gene: 'IPMK',+ name: 'Inositol Polyphosphate Multikinase',+ category: 'longevity',+ description: 'IPMK is involved in cellular signaling and nutrient sensing pathways. Variants may influence metabolic longevity pathways.',+ implications: {+ beneficial: 'Genotype associated with favorable metabolic signaling.',+ typical: 'Intermediate variant — standard metabolic signaling.',+ concern: 'No longevity-associated variant detected.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'typical' },+ { genotypes: ['T/T'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs1042522',+ gene: 'TP53',+ name: 'Tumor Protein p53 (Pro72Arg)',+ category: 'tumor_suppression',+ description: 'TP53 is the guardian of the genome. The Pro72Arg polymorphism affects apoptotic efficiency. Arg (G) induces apoptosis more efficiently, while Pro (C) favors cell cycle arrest and DNA repair.',+ implications: {+ beneficial: 'Arg/Arg — more efficient apoptotic response to DNA damage.',+ typical: 'Heterozygous — balanced apoptosis and repair capacity.',+ concern: 'Pro/Pro — favors repair over apoptosis, which may affect tumor suppression efficiency.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['C/G', 'G/C'], status: 'typical' },+ { genotypes: ['C/C'], status: 'concern' }+ ]+ },++ // === IRON METABOLISM ===+ {+ rsid: 'rs1799945',+ gene: 'HFE (H63D)',+ name: 'Hereditary Hemochromatosis H63D',+ category: 'iron',+ description: 'H63D is a common HFE variant associated with mild iron overload. Homozygous carriers have moderately increased iron absorption.',+ implications: {+ beneficial: 'No H63D variant — normal iron regulation.',+ concern: 'Heterozygous carrier — mildly increased iron absorption. Monitor ferritin levels.',+ major_concern: 'Homozygous H63D — moderate hemochromatosis risk. Regular iron panel monitoring recommended.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/G', 'G/C'], status: 'concern' },+ { genotypes: ['G/G'], status: 'major_concern' }+ ]+ },+ {+ rsid: 'rs1800562',+ gene: 'HFE (C282Y)',+ name: 'Hereditary Hemochromatosis C282Y',+ category: 'iron',+ description: 'C282Y is the primary HFE mutation for hereditary hemochromatosis. Homozygous carriers have significantly increased iron absorption and organ damage risk.',+ implications: {+ beneficial: 'No C282Y variant — normal iron regulation.',+ concern: 'Heterozygous carrier — mild hemochromatosis risk. Compound heterozygosity with H63D increases risk.',+ major_concern: 'Homozygous C282Y — high hereditary hemochromatosis risk. Regular phlebotomy and monitoring essential.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['A/G', 'G/A'], status: 'concern' },+ { genotypes: ['A/A'], status: 'major_concern' }+ ]+ },++ // === METHYLATION ===+ {+ rsid: 'rs1801133',+ gene: 'MTHFR',+ name: 'MTHFR C677T',+ category: 'methylation',+ description: 'MTHFR C677T affects folate metabolism and homocysteine levels. The T variant reduces enzyme activity, impacting methylation capacity.',+ implications: {+ beneficial: 'C/C — normal MTHFR enzyme activity (~100%). Standard folate metabolism.',+ concern: 'C/T heterozygous — ~65% enzyme activity. Consider methylfolate supplementation.',+ major_concern: 'T/T homozygous — ~30% enzyme activity. Elevated homocysteine risk. Methylfolate supplementation recommended.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'concern' },+ { genotypes: ['T/T'], status: 'major_concern' }+ ]+ },+ {+ rsid: 'rs1801131',+ gene: 'MTHFR',+ name: 'MTHFR A1298C',+ category: 'methylation',+ description: 'MTHFR A1298C is a second common variant affecting methylation. Less impactful alone than C677T, but compound heterozygosity (one copy of each) can significantly reduce function.',+ implications: {+ beneficial: 'T/T — normal MTHFR activity at this position.',+ concern: 'Heterozygous — mildly reduced activity. Check for compound heterozygosity with C677T.',+ major_concern: 'Homozygous variant — reduced activity at both MTHFR positions increases methylation impact.'+ },+ rules: [+ { genotypes: ['T/T'], status: 'beneficial' },+ { genotypes: ['G/T', 'T/G'], status: 'concern' },+ { genotypes: ['G/G'], status: 'major_concern' }+ ]+ },+ {+ rsid: 'rs4680',+ gene: 'COMT',+ name: 'COMT Val158Met',+ category: 'methylation',+ description: 'COMT metabolizes catecholamines (dopamine, norepinephrine) in the prefrontal cortex. Val (G) = fast breakdown ("Warrior" — stress-resilient), Met (A) = slow breakdown ("Worrier" — better focus in calm). Neither is inherently better — context matters.',+ implications: {+ beneficial: 'A/G heterozygous — balanced COMT activity. Often considered optimal for both focus and stress resilience.',+ typical: 'G/G Val/Val — fast COMT. Lower dopamine baseline. Better stress resilience, may need more stimulation for focus.',+ concern: 'A/A Met/Met — slow COMT. Higher dopamine baseline. Better focus under calm conditions, but more stress-sensitive.'+ },+ rules: [+ { genotypes: ['A/G', 'G/A'], status: 'beneficial' },+ { genotypes: ['G/G'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs819147',+ gene: 'AHCY',+ name: 'S-Adenosylhomocysteine Hydrolase',+ category: 'methylation',+ description: 'AHCY converts S-adenosylhomocysteine to homocysteine in the methylation cycle. Variants can affect methylation efficiency and homocysteine clearance.',+ implications: {+ beneficial: 'Normal AHCY function — efficient methylation cycle turnover.',+ typical: 'Heterozygous — mildly altered AHCY activity.',+ concern: 'Homozygous variant — may affect methylation cycle efficiency.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'typical' },+ { genotypes: ['T/T'], status: 'concern' }+ ]+ },++ // === CAFFEINE ===+ {+ rsid: 'rs73598374',+ gene: 'ADA',+ name: 'Caffeine / Adenosine Processing',+ category: 'caffeine',+ description: 'ADA (adenosine deaminase) breaks down adenosine, the molecule caffeine blocks. Variants affect caffeine sensitivity and sleep quality after caffeine consumption.',+ implications: {+ beneficial: 'C/C — normal adenosine processing. Standard caffeine response.',+ concern: 'C/T — altered adenosine metabolism. May be more sensitive to caffeine effects on sleep.',+ major_concern: 'T/T — significantly altered adenosine processing. Likely high caffeine sensitivity.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'concern' },+ { genotypes: ['T/T'], status: 'major_concern' }+ ]+ },++ // === DETOXIFICATION ===+ {+ rsid: 'rs3745274',+ gene: 'CYP2B6',+ name: 'Drug Metabolism / CYP2B6',+ category: 'detox',+ description: 'CYP2B6 metabolizes many drugs including efavirenz, bupropion, and cyclophosphamide. Variants affect metabolism speed and drug response.',+ implications: {+ beneficial: 'G/G — normal (extensive) metabolizer. Standard drug metabolism.',+ typical: 'G/T — intermediate metabolizer. May need dose adjustments for some medications.',+ concern: 'T/T — poor metabolizer. Significantly altered drug metabolism. Pharmacogenomic testing recommended before certain medications.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['G/T', 'T/G'], status: 'typical' },+ { genotypes: ['T/T'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs4880',+ gene: 'SOD2',+ name: 'Superoxide Dismutase / Oxidative Stress',+ category: 'detox',+ description: 'SOD2 (MnSOD) neutralizes superoxide radicals in mitochondria. The Ala16Val polymorphism affects mitochondrial targeting and antioxidant capacity.',+ implications: {+ beneficial: 'A/G heterozygous — balanced SOD2 activity. Heterozygote advantage documented in some studies.',+ typical: 'G/G Ala/Ala — efficient mitochondrial import. Good baseline antioxidant capacity.',+ concern: 'A/A Val/Val — less efficient mitochondrial targeting. May benefit from additional antioxidant support.'+ },+ rules: [+ { genotypes: ['A/G', 'G/A'], status: 'beneficial' },+ { genotypes: ['G/G'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },++ // === INFLAMMATION ===+ {+ rsid: 'rs1800795',+ gene: 'IL-6',+ name: 'Interleukin-6 Inflammation',+ category: 'inflammation',+ description: 'IL-6 is a key inflammatory cytokine. The -174 G/C promoter polymorphism affects IL-6 expression levels and systemic inflammation.',+ implications: {+ beneficial: 'G/G — lower baseline IL-6 levels. Reduced systemic inflammation.',+ typical: 'G/C — intermediate IL-6 expression.',+ concern: 'C/C — higher baseline IL-6 levels. Associated with increased inflammatory response and cardiovascular risk.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['G/C', 'C/G'], status: 'typical' },+ { genotypes: ['C/C'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs1800629',+ gene: 'TNF-alpha',+ name: 'TNF-alpha Inflammatory Response',+ category: 'inflammation',+ description: 'TNF-alpha is a master regulator of the inflammatory cascade. The -308 G>A promoter variant increases TNF-alpha production, raising risk for autoimmune and inflammatory conditions.',+ implications: {+ beneficial: 'G/G — normal TNF-alpha expression. Standard inflammatory baseline.',+ typical: 'G/A — moderately elevated TNF-alpha. Slightly increased inflammatory tendency.',+ concern: 'A/A — significantly elevated TNF-alpha production. Higher risk for rheumatoid arthritis, inflammatory bowel disease, and other autoimmune conditions.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['G/A', 'A/G'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },++ // === CARDIOVASCULAR ===+ {+ rsid: 'rs6025',+ gene: 'F5 (Factor V)',+ name: 'Factor V Leiden Thrombophilia',+ category: 'cardiovascular',+ description: 'Factor V Leiden is the most common inherited thrombophilia. The variant makes Factor V resistant to inactivation by Protein C, increasing venous clot risk 5-80x depending on zygosity.',+ implications: {+ beneficial: 'C/C — no Factor V Leiden variant. Normal clotting regulation.',+ concern: 'C/T — heterozygous carrier. 5-10x increased risk of venous thromboembolism. Discuss with physician before surgery, hormonal contraceptives, or long flights.',+ major_concern: 'T/T — homozygous Factor V Leiden. 50-100x increased clotting risk. Anticoagulation management strongly recommended.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'concern' },+ { genotypes: ['T/T'], status: 'major_concern' }+ ]+ },+ {+ rsid: 'rs1333049',+ gene: '9p21.3',+ name: 'Coronary Artery Disease Risk (9p21)',+ category: 'cardiovascular',+ description: 'The 9p21.3 locus is the strongest common genetic risk factor for coronary artery disease, replicated in >100,000 individuals across multiple ethnicities. It affects vascular cell proliferation near CDKN2A/B tumor suppressors.',+ implications: {+ beneficial: 'G/G — lower genetic risk for coronary artery disease.',+ typical: 'C/G — average population risk. One copy of risk allele.',+ concern: 'C/C — elevated genetic risk (~1.6x) for coronary artery disease. Extra emphasis on modifiable risk factors (diet, exercise, lipids).'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['C/G', 'G/C'], status: 'typical' },+ { genotypes: ['C/C'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs10455872',+ gene: 'LPA',+ name: 'Lipoprotein(a) Levels',+ category: 'cardiovascular',+ description: 'Lipoprotein(a) is a causal, independent cardiovascular risk factor not lowered by statins. This LPA variant strongly predicts elevated Lp(a) levels. High Lp(a) increases risk of heart attack, stroke, and aortic stenosis.',+ implications: {+ beneficial: 'A/A — predicted normal Lp(a) levels.',+ concern: 'A/G — likely elevated Lp(a). Request a blood Lp(a) measurement to confirm. Consider PCSK9 inhibitors or emerging therapies if confirmed high.',+ major_concern: 'G/G — strongly elevated Lp(a) predicted. High cardiovascular risk independent of LDL. Lp(a) blood test and cardiology consultation recommended.'+ },+ rules: [+ { genotypes: ['A/A'], status: 'beneficial' },+ { genotypes: ['A/G', 'G/A'], status: 'concern' },+ { genotypes: ['G/G'], status: 'major_concern' }+ ]+ },+ {+ rsid: 'rs1799963',+ gene: 'F2 (Prothrombin)',+ name: 'Prothrombin G20210A Thrombophilia',+ category: 'cardiovascular',+ description: 'The prothrombin G20210A mutation increases prothrombin production, raising venous thromboembolism risk 2-5x. Second most common inherited thrombophilia after Factor V Leiden.',+ implications: {+ beneficial: 'G/G — normal prothrombin levels. No inherited thrombophilia from this variant.',+ concern: 'G/A — heterozygous carrier. ~3x increased venous clot risk. Combined with Factor V Leiden or oral contraceptives, risk compounds significantly.',+ major_concern: 'A/A — homozygous variant. Substantially elevated clotting risk. Hematology consultation recommended.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['G/A', 'A/G'], status: 'concern' },+ { genotypes: ['A/A'], status: 'major_concern' }+ ]+ },++ // === NUTRIENT METABOLISM ===+ {+ rsid: 'rs2228570',+ gene: 'VDR',+ name: 'Vitamin D Receptor (FokI)',+ category: 'nutrient',+ description: 'The VDR FokI polymorphism affects Vitamin D receptor length and activity. The shorter "F" form (T allele on + strand) is more transcriptionally active, influencing calcium absorption, bone density, and immune function.',+ implications: {+ beneficial: 'T/T — more active VDR. Better vitamin D utilization at a given blood level.',+ typical: 'C/T — intermediate VDR activity.',+ concern: 'C/C — less active VDR. May require higher vitamin D levels to achieve the same biological effect. Consider testing 25(OH)D levels.'+ },+ rules: [+ { genotypes: ['T/T'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'typical' },+ { genotypes: ['C/C'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs7501331',+ gene: 'BCMO1',+ name: 'Beta-Carotene to Vitamin A Conversion',+ category: 'nutrient',+ description: 'BCMO1 converts beta-carotene (from plants) into retinal (active Vitamin A). Variants reduce conversion efficiency by 32-69%, meaning plant-based beta-carotene may not meet Vitamin A needs.',+ implications: {+ beneficial: 'C/C — normal beta-carotene conversion. Plant sources can meet Vitamin A needs.',+ concern: 'C/T — ~32% reduced conversion. May need more preformed Vitamin A (retinol) from animal sources or supplements.',+ major_concern: 'T/T — ~69% reduced conversion. Significantly impaired beta-carotene utilization. Preformed Vitamin A sources recommended.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'concern' },+ { genotypes: ['T/T'], status: 'major_concern' }+ ]+ },+ {+ rsid: 'rs602662',+ gene: 'FUT2',+ name: 'Vitamin B12 Absorption (Secretor Status)',+ category: 'nutrient',+ description: 'FUT2 determines "secretor status" — whether you secrete blood type antigens into mucus and saliva. Non-secretors have altered gut microbiome composition and reduced Vitamin B12 absorption.',+ implications: {+ beneficial: 'G/G — secretor. Normal B12 absorption and gut microbiome interaction.',+ typical: 'A/G — secretor (one functional copy sufficient). Generally adequate B12 absorption.',+ concern: 'A/A — non-secretor (~20% of population). Reduced B12 absorption. Monitor B12 levels, especially on plant-based diets. Also associated with resistance to norovirus.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['A/G', 'G/A'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs4588',+ gene: 'GC (VDBP)',+ name: 'Vitamin D Binding Protein',+ category: 'nutrient',+ description: 'GC encodes the Vitamin D binding protein that transports vitamin D in blood. Variants affect circulating 25(OH)D levels and bioavailability. This is one of the strongest genetic determinants of vitamin D status.',+ implications: {+ beneficial: 'C/C — normal VDBP function. Standard vitamin D transport and bioavailability.',+ typical: 'A/C — intermediate effect on vitamin D levels.',+ concern: 'A/A — associated with lower circulating 25(OH)D levels. May need higher supplementation doses to achieve optimal vitamin D status.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['A/C', 'C/A'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },++ // === CAFFEINE (additional) ===+ {+ rsid: 'rs762551',+ gene: 'CYP1A2',+ name: 'Caffeine Metabolism Speed',+ category: 'caffeine',+ description: 'CYP1A2 is the primary liver enzyme that metabolizes caffeine. This is the classic "fast vs slow caffeine metabolizer" SNP. Fast metabolizers clear caffeine quickly; slow metabolizers experience prolonged stimulation and higher cardiovascular risk from heavy coffee consumption.',+ implications: {+ beneficial: 'A/A — fast metabolizer. Caffeine is cleared quickly. Moderate coffee consumption may even be cardioprotective.',+ typical: 'A/C — intermediate metabolizer. Moderate caffeine tolerance.',+ concern: 'C/C — slow metabolizer. Caffeine lingers ~4x longer. Associated with increased heart attack risk from heavy coffee consumption (>3 cups/day). Consider limiting intake, especially afternoon and evening.'+ },+ rules: [+ { genotypes: ['A/A'], status: 'beneficial' },+ { genotypes: ['A/C', 'C/A'], status: 'typical' },+ { genotypes: ['C/C'], status: 'concern' }+ ]+ },++ // === DETOXIFICATION (additional) ===+ {+ rsid: 'rs4244285',+ gene: 'CYP2C19',+ name: 'Drug Metabolism / CYP2C19',+ category: 'detox',+ description: 'CYP2C19 metabolizes proton pump inhibitors (omeprazole), antidepressants (citalopram), and antiplatelet drugs (clopidogrel). Poor metabolizers may not activate clopidogrel, risking treatment failure after cardiac stents.',+ implications: {+ beneficial: 'G/G — normal (extensive) metabolizer. Standard drug activation and clearance.',+ typical: 'G/A — intermediate metabolizer. Some drugs may need dose adjustment.',+ concern: 'A/A — poor metabolizer. Clopidogrel may be ineffective. PPIs may accumulate. FDA recommends alternative antiplatelet therapy for CYP2C19 poor metabolizers with cardiac stents.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['G/A', 'A/G'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs1800566',+ gene: 'NQO1',+ name: 'Quinone Detoxification (NQO1)',+ category: 'detox',+ description: 'NQO1 detoxifies quinones from diet and environment, preventing oxidative DNA damage. The C609T variant eliminates enzyme activity, reducing protection against benzene toxicity and certain chemotherapy metabolism.',+ implications: {+ beneficial: 'C/C — full NQO1 activity. Normal quinone detoxification and benzene protection.',+ typical: 'C/T — ~50% enzyme activity. Mildly reduced detoxification capacity.',+ concern: 'T/T — no functional NQO1 enzyme. Increased sensitivity to benzene exposure and oxidative stress. Avoid unnecessary chemical exposures.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'typical' },+ { genotypes: ['T/T'], status: 'concern' }+ ]+ },++ // === COGNITIVE ===+ {+ rsid: 'rs6265',+ gene: 'BDNF',+ name: 'Brain-Derived Neurotrophic Factor (Val66Met)',+ category: 'cognitive',+ description: 'BDNF is critical for neuroplasticity, memory formation, and mood regulation. The Val66Met polymorphism affects activity-dependent BDNF secretion in the brain. Met carriers have reduced hippocampal volume and altered stress response.',+ implications: {+ beneficial: 'G/G (Val/Val) — normal activity-dependent BDNF secretion. Standard neuroplasticity and memory consolidation.',+ typical: 'A/G (Val/Met) — reduced activity-dependent secretion (~25%). May benefit from regular exercise, which strongly upregulates BDNF.',+ concern: 'A/A (Met/Met) — significantly reduced BDNF secretion. Associated with smaller hippocampal volume, altered stress response, and increased depression susceptibility. Exercise is particularly beneficial for this genotype.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['A/G', 'G/A'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },++ // === SLEEP & CIRCADIAN ===+ {+ rsid: 'rs1801260',+ gene: 'CLOCK',+ name: 'Circadian Clock Gene',+ category: 'sleep',+ description: 'CLOCK is a core circadian rhythm gene. The 3111T>C variant is associated with evening chronotype preference, later sleep onset, shorter sleep duration, and higher resistance to sleep deprivation.',+ implications: {+ beneficial: 'T/T — standard circadian rhythm. Typical sleep-wake preferences.',+ typical: 'T/C — mild evening tendency. Slightly delayed sleep preference.',+ concern: 'C/C — strong evening chronotype. Delayed sleep phase, reduced sleep duration. May struggle with early schedules. Melatonin timing and light exposure management may help.'+ },+ rules: [+ { genotypes: ['T/T'], status: 'beneficial' },+ { genotypes: ['T/C', 'C/T'], status: 'typical' },+ { genotypes: ['C/C'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs57875989',+ gene: 'DEC2/BHLHE41',+ name: 'Short Sleep Gene',+ category: 'sleep',+ description: 'DEC2 (BHLHE41) regulates sleep duration. The rare "short sleeper" mutation allows healthy function on 4-6 hours of sleep without cognitive impairment. Extremely rare (~1% of population).',+ implications: {+ beneficial: 'Carrier of short-sleep variant — may genuinely require less sleep without health consequences.',+ typical: 'No short-sleep variant — standard 7-9 hour sleep requirement for optimal health.'+ },+ rules: [+ { genotypes: ['A/G', 'G/A'], status: 'beneficial' },+ { genotypes: ['G/G'], status: 'typical' },+ { genotypes: ['A/A'], status: 'beneficial' }+ ]+ },++ // === ATHLETIC PERFORMANCE ===+ {+ rsid: 'rs1815739',+ gene: 'ACTN3',+ name: 'Muscle Fiber Type (Sprint vs Endurance)',+ category: 'athletic',+ description: 'ACTN3 encodes alpha-actinin-3, a protein found exclusively in fast-twitch muscle fibers. The R577X polymorphism determines whether you produce it. ~18% of people worldwide are X/X (no alpha-actinin-3), favoring endurance over sprint/power.',+ implications: {+ beneficial: 'C/C (R/R) — alpha-actinin-3 present. Fast-twitch muscle fibers fully functional. Advantage in sprint, power, and strength activities.',+ typical: 'C/T (R/X) — one functional copy. Mixed fiber profile. Versatile across power and endurance.',+ concern: 'T/T (X/X) — no alpha-actinin-3. Fast-twitch fibers remodeled toward slow-twitch. Natural endurance advantage but reduced peak power output. Not pathological — many elite endurance athletes carry this genotype.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'typical' },+ { genotypes: ['T/T'], status: 'concern' }+ ]+ },+ {+ rsid: 'rs4341',+ gene: 'ACE',+ name: 'ACE Insertion/Deletion (Endurance)',+ category: 'athletic',+ description: 'The ACE I/D polymorphism affects angiotensin-converting enzyme levels. The I allele (lower ACE) is associated with endurance performance and altitude adaptation. The D allele (higher ACE) is associated with power/sprint performance.',+ implications: {+ beneficial: 'G/G — associated with endurance-favorable ACE levels.',+ typical: 'A/G — mixed profile. Balanced endurance and power potential.',+ concern: 'A/A — associated with higher ACE activity. Power-oriented physiology, but also linked to higher blood pressure and cardiovascular strain during prolonged endurance exercise.'+ },+ rules: [+ { genotypes: ['G/G'], status: 'beneficial' },+ { genotypes: ['A/G', 'G/A'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ },++ // === SKIN & UV RESPONSE ===+ {+ rsid: 'rs1805007',+ gene: 'MC1R',+ name: 'Melanin Type / UV Sensitivity',+ category: 'skin',+ description: 'MC1R controls the switch between eumelanin (dark, UV-protective) and pheomelanin (red/yellow, UV-sensitizing). This R151C variant is strongly associated with red hair, fair skin, freckling, and increased melanoma risk.',+ implications: {+ beneficial: 'C/C — normal MC1R function. Standard eumelanin production and UV protection.',+ typical: 'C/T — one variant copy. Mildly increased UV sensitivity and freckling tendency.',+ concern: 'T/T — strongly reduced MC1R function. Fair skin, high UV sensitivity, 2-4x melanoma risk. Rigorous sun protection essential.'+ },+ rules: [+ { genotypes: ['C/C'], status: 'beneficial' },+ { genotypes: ['C/T', 'T/C'], status: 'typical' },+ { genotypes: ['T/T'], status: 'concern' }+ ]+ },++ // === METABOLIC ===+ {+ rsid: 'rs9939609',+ gene: 'FTO',+ name: 'Fat Mass & Obesity Associated Gene',+ category: 'longevity',+ description: 'FTO is the strongest common genetic contributor to obesity risk. The A allele increases appetite, reduces satiety signaling, and is associated with higher BMI. Each A allele adds ~1.5kg average weight. Effect is substantially modifiable by physical activity.',+ implications: {+ beneficial: 'T/T — lower genetic obesity risk. Standard appetite regulation.',+ typical: 'A/T — one risk allele. Modestly increased obesity risk (~1.2x). Regular physical activity largely negates the effect.',+ concern: 'A/A — two risk alleles (~1.7x obesity risk). Reduced satiety signaling. Physically active A/A carriers show almost no excess risk — exercise is the most effective countermeasure for this genotype.'+ },+ rules: [+ { genotypes: ['T/T'], status: 'beneficial' },+ { genotypes: ['A/T', 'T/A'], status: 'typical' },+ { genotypes: ['A/A'], status: 'concern' }+ ]+ }+];++/**+ * Format raw genotype (e.g., "CT") to display format (e.g., "C/T").+ * Handles already-formatted genotypes, single alleles, and edge cases.+ */+export function formatGenotype(raw) {+ if (!raw || raw === '--' || raw === '00') return null;+ const cleaned = raw.trim().toUpperCase();+ if (cleaned.includes('/')) return cleaned;+ if (cleaned.length === 2) return `${cleaned[0]}/${cleaned[1]}`;+ if (cleaned.length === 1) return `${cleaned}/${cleaned}`;+ return cleaned;+}++/**+ * Classify a genotype against a curated marker's rules.+ * Returns a status string: 'beneficial', 'typical', 'concern', 'major_concern', or 'not_found'.+ */+export function classifyGenotype(marker, genotype) {+ if (!genotype) return 'not_found';+ const formatted = formatGenotype(genotype);+ if (!formatted) return 'not_found';++ for (const rule of marker.rules) {+ if (rule.genotypes.includes(formatted)) {+ return rule.status;+ }+ }+ // If genotype doesn't match any known rule, return typical as fallback+ return 'typical';+}diff --git a/server/lib/genomeValidation.js b/server/lib/genomeValidation.jsnew file mode 100644index 0000000000..2bed85c10e--- /dev/null+++ b/server/lib/genomeValidation.js@@ -0,0 +1,29 @@+import { z } from 'zod';++export const genomeUploadSchema = z.object({+ content: z.string().min(100, 'Genome file content too short'),+ filename: z.string().min(1, 'Filename required')+});++export const genomeSearchSchema = z.object({+ rsid: z.string().regex(/^rs\d+$/, 'Must be a valid rsid (e.g., rs1234)')+});++export const genomeSaveMarkerSchema = z.object({+ rsid: z.string().regex(/^rs\d+$/),+ genotype: z.string().optional(),+ chromosome: z.string().optional(),+ position: z.string().optional(),+ name: z.string().min(1).max(200),+ category: z.string().min(1).max(50),+ gene: z.string().max(100).optional().default(''),+ description: z.string().max(2000).optional().default(''),+ implications: z.string().max(2000).optional().default(''),+ status: z.enum(['beneficial', 'typical', 'concern', 'major_concern', 'not_found']).optional().default('typical'),+ notes: z.string().max(5000).optional().default(''),+ references: z.array(z.string().url()).optional().default([])+});++export const genomeUpdateNotesSchema = z.object({+ notes: z.string().max(5000)+});diff --git a/server/routes/genome.js b/server/routes/genome.jsnew file mode 100644index 0000000000..ab29e6c8f3--- /dev/null+++ b/server/routes/genome.js@@ -0,0 +1,182 @@+import { Router } from 'express';+import * as genomeService from '../services/genome.js';+import * as clinvarService from '../services/clinvar.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validate } from '../lib/validation.js';+import {+ genomeUploadSchema,+ genomeSearchSchema,+ genomeSaveMarkerSchema,+ genomeUpdateNotesSchema+} from '../lib/genomeValidation.js';++const router = Router();++// GET /api/digital-twin/genome — Summary+router.get('/', asyncHandler(async (req, res) => {+ const summary = await genomeService.getGenomeSummary();+ res.json(summary);+}));++// POST /api/digital-twin/genome/upload — Upload genome file+router.post('/upload', asyncHandler(async (req, res) => {+ const validation = validate(genomeUploadSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', {+ status: 400,+ code: 'VALIDATION_ERROR',+ context: { details: validation.errors }+ });+ }++ const result = await genomeService.uploadGenome(validation.data.content, validation.data.filename);+ if (result.error) {+ throw new ServerError(result.error, {+ status: 400,+ code: 'GENOME_UPLOAD_ERROR'+ });+ }++ res.status(201).json(result);+}));++// POST /api/digital-twin/genome/scan — Scan curated markers+router.post('/scan', asyncHandler(async (req, res) => {+ const result = await genomeService.scanCuratedMarkers();+ if (result.error) {+ throw new ServerError(result.error, {+ status: 400,+ code: 'GENOME_SCAN_ERROR'+ });+ }++ res.json(result);+}));++// POST /api/digital-twin/genome/search — Search SNP by rsid+router.post('/search', asyncHandler(async (req, res) => {+ const validation = validate(genomeSearchSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', {+ status: 400,+ code: 'VALIDATION_ERROR',+ context: { details: validation.errors }+ });+ }++ const result = await genomeService.searchSNP(validation.data.rsid);+ res.json(result);+}));++// POST /api/digital-twin/genome/markers — Save a marker+router.post('/markers', asyncHandler(async (req, res) => {+ const validation = validate(genomeSaveMarkerSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', {+ status: 400,+ code: 'VALIDATION_ERROR',+ context: { details: validation.errors }+ });+ }++ const marker = await genomeService.saveMarker(validation.data);+ res.status(201).json(marker);+}));++// PUT /api/digital-twin/genome/markers/:id/notes — Update marker notes+router.put('/markers/:id/notes', asyncHandler(async (req, res) => {+ const validation = validate(genomeUpdateNotesSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', {+ status: 400,+ code: 'VALIDATION_ERROR',+ context: { details: validation.errors }+ });+ }++ const result = await genomeService.updateMarkerNotes(req.params.id, validation.data.notes);+ if (result.error) {+ throw new ServerError(result.error, {+ status: 404,+ code: 'MARKER_NOT_FOUND'+ });+ }++ res.json(result);+}));++// DELETE /api/digital-twin/genome/markers/:id — Delete a marker+router.delete('/markers/:id', asyncHandler(async (req, res) => {+ const result = await genomeService.deleteMarker(req.params.id);+ if (result.error) {+ throw new ServerError(result.error, {+ status: 404,+ code: 'MARKER_NOT_FOUND'+ });+ }++ res.status(204).end();+}));++// === ClinVar Routes ===++// GET /api/digital-twin/genome/clinvar/status — ClinVar sync status+router.get('/clinvar/status', asyncHandler(async (req, res) => {+ const status = await clinvarService.getClinvarStatus();+ res.json(status);+}));++// POST /api/digital-twin/genome/clinvar/sync — Download and index ClinVar database+router.post('/clinvar/sync', asyncHandler(async (req, res) => {+ const io = req.app.get('io');+ const onProgress = (message) => {+ if (io) io.emit('genome:clinvar-progress', { message });+ };++ const result = await clinvarService.syncClinvar(onProgress);+ if (result.error) {+ throw new ServerError(result.error, {+ status: 500,+ code: 'CLINVAR_SYNC_ERROR'+ });+ }++ clinvarService.invalidateClinvarCache();+ res.json(result);+}));++// POST /api/digital-twin/genome/clinvar/scan — Scan genome against ClinVar+router.post('/clinvar/scan', asyncHandler(async (req, res) => {+ const snpIndex = await genomeService.getSnpIndex();+ if (!snpIndex) {+ throw new ServerError('No genome data uploaded', {+ status: 400,+ code: 'NO_GENOME_DATA'+ });+ }++ const result = await clinvarService.scanClinvar(snpIndex);+ if (result.error) {+ throw new ServerError(result.error, {+ status: 400,+ code: 'CLINVAR_SCAN_ERROR'+ });+ }++ res.json(result);+}));++// DELETE /api/digital-twin/genome/clinvar — Delete ClinVar data+router.delete('/clinvar', asyncHandler(async (req, res) => {+ await clinvarService.deleteClinvar();+ res.status(204).end();+}));++// DELETE /api/digital-twin/genome — Delete all genome data+router.delete('/', asyncHandler(async (req, res) => {+ await genomeService.deleteGenome();+ await clinvarService.deleteClinvar();+ res.status(204).end();+}));++export default router;diff --git a/server/services/clinvar.js b/server/services/clinvar.jsnew file mode 100644index 0000000000..bdd45b1403--- /dev/null+++ b/server/services/clinvar.js@@ -0,0 +1,378 @@+import { createWriteStream, createReadStream } from 'fs';+import { readFile, writeFile, stat, unlink } from 'fs/promises';+import { join } from 'path';+import { createGunzip } from 'zlib';+import { createInterface } from 'readline';+import { pipeline } from 'stream/promises';+import { PATHS, ensureDir } from '../lib/fileUtils.js';++const GENOME_DIR = PATHS.digitalTwin;+const CLINVAR_GZ = join(GENOME_DIR, 'clinvar-raw.txt.gz');+const CLINVAR_INDEX = join(GENOME_DIR, 'clinvar-index.json');+const CLINVAR_META = join(GENOME_DIR, 'clinvar-meta.json');++const CLINVAR_URL = 'https://ftp.ncbi.nlm.nih.gov/pub/clinvar/tab_delimited/variant_summary.txt.gz';++// ClinVar significance levels we care about (skip benign/uncertain — too noisy)+const ACTIONABLE_SIGNIFICANCE = new Set([+ 'pathogenic',+ 'likely pathogenic',+ 'pathogenic/likely pathogenic',+ 'risk factor',+ 'drug response',+ 'association',+ 'protective',+ 'affects',+ 'pathogenic, risk factor',+ 'likely pathogenic, risk factor'+]);++// Map review status to star rating (ClinVar's official star system)+const REVIEW_STARS = {+ 'practice guideline': 4,+ 'reviewed by expert panel': 3,+ 'criteria provided, multiple submitters, no conflicts': 2,+ 'criteria provided, conflicting classifications': 1,+ 'criteria provided, single submitter': 1+};++// In-memory index: Map<rsid, array of annotations>+let clinvarIndex = null;++/**+ * Get ClinVar sync status and stats.+ */+export async function getClinvarStatus() {+ await ensureDir(GENOME_DIR);+ const meta = await readFile(CLINVAR_META, 'utf-8').catch(() => null);+ if (!meta) return { synced: false };+ return JSON.parse(meta);+}++/**+ * Download ClinVar variant_summary.txt.gz from NCBI FTP.+ * Returns the path to the downloaded file.+ */+async function downloadClinvar(onProgress) {+ await ensureDir(GENOME_DIR);++ console.log('🧬 ClinVar: downloading variant_summary.txt.gz from NCBI...');+ onProgress?.('Downloading ClinVar database from NCBI...');++ const response = await fetch(CLINVAR_URL);+ if (!response.ok) {+ return { error: `Download failed: HTTP ${response.status}` };+ }++ const totalBytes = parseInt(response.headers.get('content-length') || '0', 10);+ const writer = createWriteStream(CLINVAR_GZ);+ const reader = response.body.getReader();++ let downloaded = 0;+ const writable = new WritableStream({+ write(chunk) {+ downloaded += chunk.length;+ writer.write(chunk);+ if (totalBytes > 0) {+ const pct = Math.round((downloaded / totalBytes) * 100);+ if (pct % 10 === 0) onProgress?.(`Downloading... ${pct}% (${(downloaded / 1024 / 1024).toFixed(1)}MB)`);+ }+ },+ close() {+ writer.end();+ }+ });++ await reader.read().then(function pump({ done, value }) {+ if (done) {+ writer.end();+ return;+ }+ downloaded += value.length;+ writer.write(value);+ if (totalBytes > 0) {+ const pct = Math.round((downloaded / totalBytes) * 100);+ if (pct % 10 === 0) onProgress?.(`Downloading... ${pct}% (${(downloaded / 1024 / 1024).toFixed(1)}MB)`);+ }+ return reader.read().then(pump);+ });++ // Wait for writer to finish+ await new Promise((resolve, reject) => {+ writer.on('finish', resolve);+ writer.on('error', reject);+ });++ const fileInfo = await stat(CLINVAR_GZ);+ console.log(`🧬 ClinVar: downloaded ${(fileInfo.size / 1024 / 1024).toFixed(1)}MB`);++ return { path: CLINVAR_GZ, size: fileInfo.size };+}++/**+ * Parse the ClinVar gzipped TSV and build a filtered index.+ * Streams the file to handle large sizes without loading into memory.+ */+async function buildClinvarIndex(onProgress) {+ console.log('🧬 ClinVar: parsing and filtering variant_summary.txt.gz...');+ onProgress?.('Parsing ClinVar data (this may take a minute)...');++ const index = {};+ let lineCount = 0;+ let matchCount = 0;+ let headerColumns = null;++ await new Promise((resolve, reject) => {+ const gunzip = createGunzip();+ const fileStream = createReadStream(CLINVAR_GZ);+ const rl = createInterface({ input: fileStream.pipe(gunzip) });++ rl.on('line', (line) => {+ lineCount++;++ // Parse header — strip only the leading '#' from the line (preserves '#' within column names like 'RS# (dbSNP)')+ if (lineCount === 1) {+ const headerLine = line.startsWith('#') ? line.substring(1) : line;+ headerColumns = headerLine.split('\t').reduce((acc, col, i) => {+ acc[col.trim()] = i;+ return acc;+ }, {});+ return;+ }++ const cols = line.split('\t');++ // Must have an rsid+ const rsid = cols[headerColumns['RS# (dbSNP)']]?.trim();+ if (!rsid || rsid === '-1' || rsid === '-') return;+ const rsidFormatted = rsid.startsWith('rs') ? rsid : `rs${rsid}`;++ // Must be a single nucleotide variant (matches 23andMe data)+ const varType = cols[headerColumns['Type']]?.trim().toLowerCase();+ if (varType !== 'single nucleotide variant') return;++ // Must have actionable clinical significance+ const rawSignificance = cols[headerColumns['ClinicalSignificance']]?.trim() || '';+ const significanceLower = rawSignificance.toLowerCase();++ // Check if any actionable significance is present+ const isActionable = [...ACTIONABLE_SIGNIFICANCE].some(s => significanceLower.includes(s));+ if (!isActionable) return;++ // Extract data+ const gene = cols[headerColumns['GeneSymbol']]?.trim() || '';+ const phenotype = cols[headerColumns['PhenotypeList']]?.trim() || '';+ const reviewStatus = cols[headerColumns['ReviewStatus']]?.trim() || '';+ const assembly = cols[headerColumns['Assembly']]?.trim() || '';+ const origin = cols[headerColumns['Origin']]?.trim() || '';++ // Prefer GRCh37 (Build 37, standard for 23andMe v4/v5) or GRCh38+ if (assembly && assembly !== 'GRCh37' && assembly !== 'GRCh38') return;++ // Only germline variants (not somatic)+ if (origin && !origin.includes('germline') && origin !== 'not provided') return;++ const stars = REVIEW_STARS[reviewStatus] || 0;++ // Determine our severity level+ let severity = 'risk_factor';+ if (significanceLower.includes('pathogenic')) severity = 'pathogenic';+ else if (significanceLower.includes('protective')) severity = 'protective';+ else if (significanceLower.includes('drug response')) severity = 'drug_response';+ else if (significanceLower.includes('association') || significanceLower.includes('risk factor')) severity = 'risk_factor';++ // Clean up phenotype — split on semicolons, deduplicate+ const conditions = [...new Set(+ phenotype.split(/[;|]/)+ .map(s => s.trim())+ .filter(s => s && s !== 'not specified' && s !== 'not provided')+ )].slice(0, 5); // Cap at 5 conditions++ // Store entry — group by rsid (some SNPs have multiple ClinVar entries)+ if (!index[rsidFormatted]) {+ index[rsidFormatted] = {+ gene,+ entries: []+ };+ }++ // Avoid duplicate condition entries+ const isDupe = index[rsidFormatted].entries.some(+ e => e.significance === rawSignificance && e.conditions.join() === conditions.join()+ );+ if (isDupe) return;++ index[rsidFormatted].entries.push({+ significance: rawSignificance,+ severity,+ conditions,+ reviewStatus,+ stars,+ assembly+ });++ matchCount++;++ if (matchCount % 5000 === 0) {+ onProgress?.(`Processed ${lineCount.toLocaleString()} lines, found ${matchCount.toLocaleString()} actionable variants...`);+ }+ });++ rl.on('close', resolve);+ rl.on('error', reject);+ gunzip.on('error', reject);+ fileStream.on('error', reject);+ });++ // Deduplicate: keep highest-star entry per rsid, consolidate conditions+ const compactIndex = {};+ for (const [rsid, data] of Object.entries(index)) {+ // Sort entries by severity (pathogenic first) then stars+ const severityOrder = { pathogenic: 0, drug_response: 1, risk_factor: 2, protective: 3 };+ data.entries.sort((a, b) => {+ const sDiff = (severityOrder[a.severity] ?? 9) - (severityOrder[b.severity] ?? 9);+ return sDiff !== 0 ? sDiff : b.stars - a.stars;+ });++ const topEntry = data.entries[0];+ const allConditions = [...new Set(data.entries.flatMap(e => e.conditions))].slice(0, 8);++ compactIndex[rsid] = {+ g: data.gene, // gene+ s: topEntry.severity, // severity+ c: allConditions, // conditions+ r: topEntry.stars, // review stars (0-4)+ x: topEntry.significance, // raw significance text+ n: data.entries.length // number of ClinVar submissions+ };+ }++ console.log(`🧬 ClinVar: ${Object.keys(compactIndex).length} unique rsids with actionable significance from ${lineCount.toLocaleString()} lines`);++ return compactIndex;+}++/**+ * Full sync: download ClinVar, parse, build index, save.+ */+export async function syncClinvar(onProgress) {+ const downloadResult = await downloadClinvar(onProgress);+ if (downloadResult.error) return downloadResult;++ onProgress?.('Building search index...');+ const index = await buildClinvarIndex(onProgress);++ // Save compact index+ const indexJson = JSON.stringify(index);+ await writeFile(CLINVAR_INDEX, indexJson);++ // Save metadata+ const meta = {+ synced: true,+ syncedAt: new Date().toISOString(),+ variantCount: Object.keys(index).length,+ downloadSize: downloadResult.size,+ indexSize: Buffer.byteLength(indexJson)+ };+ await writeFile(CLINVAR_META, JSON.stringify(meta, null, 2));++ // Clean up the raw gz file to save disk space+ await unlink(CLINVAR_GZ).catch(() => {});++ console.log(`🧬 ClinVar sync complete: ${meta.variantCount.toLocaleString()} variants indexed (${(meta.indexSize / 1024 / 1024).toFixed(1)}MB)`);++ return meta;+}++/**+ * Load the ClinVar index into memory (lazy, cached).+ */+async function loadClinvarIndex() {+ if (clinvarIndex) return clinvarIndex;++ const raw = await readFile(CLINVAR_INDEX, 'utf-8').catch(() => null);+ if (!raw) return null;++ clinvarIndex = JSON.parse(raw);+ console.log(`🧬 ClinVar index loaded: ${Object.keys(clinvarIndex).length.toLocaleString()} variants`);+ return clinvarIndex;+}++/**+ * Invalidate cached index (after re-sync).+ */+export function invalidateClinvarCache() {+ clinvarIndex = null;+}++// Severity to our status mapping+const SEVERITY_STATUS = {+ pathogenic: 'major_concern',+ risk_factor: 'concern',+ drug_response: 'concern',+ association: 'concern',+ protective: 'beneficial'+};++/**+ * Scan a genome's SNPs against the ClinVar index.+ * Returns grouped findings sorted by severity.+ */+export async function scanClinvar(snpIndex) {+ const cvIndex = await loadClinvarIndex();+ if (!cvIndex) return { error: 'ClinVar database not synced. Click "Sync ClinVar" first.' };+ if (!snpIndex) return { error: 'No genome data uploaded.' };++ const findings = [];++ for (const [rsid, snpData] of snpIndex) {+ const cv = cvIndex[rsid];+ if (!cv) continue;++ findings.push({+ rsid,+ genotype: snpData.genotype,+ chromosome: snpData.chromosome,+ position: snpData.position,+ gene: cv.g,+ severity: cv.s,+ status: SEVERITY_STATUS[cv.s] || 'concern',+ significance: cv.x,+ conditions: cv.c,+ reviewStars: cv.r,+ submissions: cv.n+ });+ }++ // Sort: pathogenic first, then by review stars (higher = more reliable)+ const severityOrder = { pathogenic: 0, drug_response: 1, risk_factor: 2, protective: 3 };+ findings.sort((a, b) => {+ const sDiff = (severityOrder[a.severity] ?? 9) - (severityOrder[b.severity] ?? 9);+ return sDiff !== 0 ? sDiff : b.reviewStars - a.reviewStars;+ });++ console.log(`🧬 ClinVar scan: ${findings.length} actionable variants found in genome`);++ return {+ findings,+ totalMatched: findings.length,+ bySeverity: {+ pathogenic: findings.filter(f => f.severity === 'pathogenic').length,+ drug_response: findings.filter(f => f.severity === 'drug_response').length,+ risk_factor: findings.filter(f => f.severity === 'risk_factor').length,+ protective: findings.filter(f => f.severity === 'protective').length+ }+ };+}++/**+ * Delete ClinVar data (index + meta + raw).+ */+export async function deleteClinvar() {+ await unlink(CLINVAR_GZ).catch(() => {});+ await unlink(CLINVAR_INDEX).catch(() => {});+ await unlink(CLINVAR_META).catch(() => {});+ clinvarIndex = null;+ console.log('🧬 ClinVar data deleted');+ return { success: true };+}diff --git a/server/services/genome.js b/server/services/genome.jsnew file mode 100644index 0000000000..70f926ca0a--- /dev/null+++ b/server/services/genome.js@@ -0,0 +1,348 @@+import { readFile, writeFile, unlink } from 'fs/promises';+import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, ensureDir } from '../lib/fileUtils.js';+import { CURATED_MARKERS, MARKER_CATEGORIES, classifyGenotype, formatGenotype } from '../lib/curatedGenomeMarkers.js';++const GENOME_DIR = PATHS.digitalTwin;+const RAW_FILE = join(GENOME_DIR, 'genome-raw.txt');+const META_FILE = join(GENOME_DIR, 'genome.json');++// In-memory index: Map<rsid, { chromosome, position, genotype }>+let snpIndex = null;+let indexBuiltAt = 0;+const INDEX_TTL_MS = 60 * 60 * 1000; // 1 hour cache++const DEFAULT_META = {+ uploaded: false,+ uploadedAt: null,+ filename: null,+ snpCount: 0,+ build: null,+ savedMarkers: {},+ lastScanAt: null+};++async function ensureGenomeDir() {+ await ensureDir(GENOME_DIR);+}++async function loadMeta() {+ await ensureGenomeDir();+ const raw = await readFile(META_FILE, 'utf-8').catch(() => null);+ if (!raw) return { ...DEFAULT_META };+ return JSON.parse(raw);+}++async function saveMeta(meta) {+ await ensureGenomeDir();+ await writeFile(META_FILE, JSON.stringify(meta, null, 2));+}++/**+ * Parse a 23andMe-format TSV genome file into a Map.+ * Format: rsid \t chromosome \t position \t genotype+ * Lines starting with # are comments/headers.+ */+export function parseGenomeFile(content) {+ const index = new Map();+ let build = null;+ const lines = content.split('\n');++ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed) continue;++ // Extract build info from header comments+ if (trimmed.startsWith('#')) {+ if (trimmed.includes('build 36')) build = 'Build 36';+ else if (trimmed.includes('build 37')) build = 'Build 37';+ else if (trimmed.includes('build 38') || trimmed.includes('GRCh38')) build = 'Build 38';+ continue;+ }++ const parts = trimmed.split('\t');+ if (parts.length < 4) continue;++ const [rsid, chromosome, position, genotype] = parts;+ if (!rsid.startsWith('rs') && !rsid.startsWith('i')) continue;++ index.set(rsid, {+ chromosome,+ position,+ genotype: genotype.trim()+ });+ }++ return { index, build };+}++/**+ * Build or return the in-memory SNP index from the raw genome file.+ * Cached for INDEX_TTL_MS (1 hour).+ */+export async function getSnpIndex() {+ if (snpIndex && (Date.now() - indexBuiltAt < INDEX_TTL_MS)) {+ return snpIndex;+ }++ const content = await readFile(RAW_FILE, 'utf-8').catch(() => null);+ if (!content) {+ snpIndex = null;+ return null;+ }++ const { index } = parseGenomeFile(content);+ snpIndex = index;+ indexBuiltAt = Date.now();+ console.log(`🧬 Genome index built: ${index.size} SNPs cached`);+ return index;+}++/**+ * Upload and store a genome file.+ * Validates TSV format, saves raw file, builds index, saves metadata.+ */+export async function uploadGenome(content, filename) {+ await ensureGenomeDir();++ const { index, build } = parseGenomeFile(content);+ if (index.size < 100) {+ return { error: 'File does not appear to be a valid 23andMe genome export (too few SNPs found)' };+ }++ // Save raw file+ await writeFile(RAW_FILE, content);++ // Cache the index+ snpIndex = index;+ indexBuiltAt = Date.now();++ // Save metadata+ const meta = await loadMeta();+ meta.uploaded = true;+ meta.uploadedAt = new Date().toISOString();+ meta.filename = filename;+ meta.snpCount = index.size;+ meta.build = build || 'Unknown';+ await saveMeta(meta);++ console.log(`🧬 Genome uploaded: ${filename} — ${index.size} SNPs, ${build || 'unknown build'}`);++ return {+ snpCount: index.size,+ build: build || 'Unknown',+ filename+ };+}++/**+ * Get genome summary: upload status, stats, and saved marker counts.+ */+export async function getGenomeSummary() {+ const meta = await loadMeta();+ if (!meta.uploaded) {+ return { uploaded: false };+ }++ const savedMarkers = Object.values(meta.savedMarkers || {});+ const statusCounts = { beneficial: 0, typical: 0, concern: 0, major_concern: 0, not_found: 0 };+ for (const marker of savedMarkers) {+ if (statusCounts[marker.status] !== undefined) {+ statusCounts[marker.status]++;+ }+ }++ return {+ uploaded: true,+ uploadedAt: meta.uploadedAt,+ filename: meta.filename,+ snpCount: meta.snpCount,+ build: meta.build,+ markerCount: savedMarkers.length,+ statusCounts,+ lastScanAt: meta.lastScanAt,+ savedMarkers: meta.savedMarkers+ };+}++/**+ * Scan all curated markers against the genome, classify genotypes, and auto-save results.+ */+export async function scanCuratedMarkers() {+ const index = await getSnpIndex();+ if (!index) {+ return { error: 'No genome data uploaded. Upload a genome file first.' };+ }++ const meta = await loadMeta();+ const results = [];++ for (const marker of CURATED_MARKERS) {+ const snp = index.get(marker.rsid);+ const genotype = snp ? formatGenotype(snp.genotype) : null;+ const status = snp ? classifyGenotype(marker, snp.genotype) : 'not_found';+ const implication = marker.implications[status] || '';++ // Check if already saved (by rsid match)+ const existingEntry = Object.entries(meta.savedMarkers || {}).find(([, m]) => m.rsid === marker.rsid);+ const id = existingEntry ? existingEntry[0] : randomUUID();++ const savedMarker = {+ rsid: marker.rsid,+ genotype,+ chromosome: snp?.chromosome || '',+ position: snp?.position || '',+ status,+ category: marker.category,+ gene: marker.gene,+ name: marker.name,+ description: marker.description,+ implications: implication,+ notes: existingEntry ? existingEntry[1].notes : '',+ references: existingEntry ? existingEntry[1].references : [],+ savedAt: existingEntry ? existingEntry[1].savedAt : new Date().toISOString()+ };++ meta.savedMarkers[id] = savedMarker;+ results.push({ id, ...savedMarker });+ }++ meta.lastScanAt = new Date().toISOString();+ await saveMeta(meta);++ console.log(`🧬 Curated scan complete: ${results.length} markers classified`);++ return {+ markers: results,+ categories: MARKER_CATEGORIES,+ scannedAt: meta.lastScanAt+ };+}++/**+ * Search for a single SNP by rsid in the genome data.+ */+export async function searchSNP(rsid) {+ const index = await getSnpIndex();+ if (!index) {+ return { found: false, error: 'No genome data uploaded' };+ }++ const snp = index.get(rsid);+ if (!snp) {+ return { found: false, rsid };+ }++ // Check if this SNP is in our curated list+ const curatedMarker = CURATED_MARKERS.find(m => m.rsid === rsid);+ const genotype = formatGenotype(snp.genotype);++ return {+ found: true,+ rsid,+ chromosome: snp.chromosome,+ position: snp.position,+ genotype,+ curated: !!curatedMarker,+ gene: curatedMarker?.gene || null,+ name: curatedMarker?.name || null,+ category: curatedMarker?.category || null,+ status: curatedMarker ? classifyGenotype(curatedMarker, snp.genotype) : null,+ description: curatedMarker?.description || null,+ implications: curatedMarker ? (curatedMarker.implications[classifyGenotype(curatedMarker, snp.genotype)] || '') : null+ };+}++/**+ * Save a custom marker to the genome metadata.+ */+export async function saveMarker(data) {+ const meta = await loadMeta();+ const id = randomUUID();++ // Look up genotype from raw data if not provided+ let genotype = data.genotype || null;+ let chromosome = data.chromosome || '';+ let position = data.position || '';++ if (!genotype) {+ const index = await getSnpIndex();+ if (index) {+ const snp = index.get(data.rsid);+ if (snp) {+ genotype = formatGenotype(snp.genotype);+ chromosome = snp.chromosome;+ position = snp.position;+ }+ }+ }++ const marker = {+ rsid: data.rsid,+ genotype,+ chromosome,+ position,+ status: data.status || 'typical',+ category: data.category,+ gene: data.gene || '',+ name: data.name,+ description: data.description || '',+ implications: data.implications || '',+ notes: data.notes || '',+ references: data.references || [],+ savedAt: new Date().toISOString()+ };++ meta.savedMarkers[id] = marker;+ await saveMeta(meta);+ console.log(`🧬 Marker saved: ${data.rsid} (${data.name})`);++ return { id, ...marker };+}++/**+ * Update notes on a saved marker.+ */+export async function updateMarkerNotes(id, notes) {+ const meta = await loadMeta();+ if (!meta.savedMarkers[id]) {+ return { error: 'Marker not found' };+ }++ meta.savedMarkers[id].notes = notes;+ await saveMeta(meta);+ console.log(`🧬 Marker notes updated: ${meta.savedMarkers[id].rsid}`);++ return { id, ...meta.savedMarkers[id] };+}++/**+ * Delete a saved marker.+ */+export async function deleteMarker(id) {+ const meta = await loadMeta();+ if (!meta.savedMarkers[id]) {+ return { error: 'Marker not found' };+ }++ const rsid = meta.savedMarkers[id].rsid;+ delete meta.savedMarkers[id];+ await saveMeta(meta);+ console.log(`🧬 Marker deleted: ${rsid}`);++ return { success: true };+}++/**+ * Delete all genome data: raw file, metadata, and clear cache.+ */+export async function deleteGenome() {+ await unlink(RAW_FILE).catch(() => {});+ await unlink(META_FILE).catch(() => {});+ snpIndex = null;+ indexBuiltAt = 0;+ console.log('🧬 Genome data deleted');++ return { success: true };+}