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: complete MeatSpace phases 2-5 — alcohol tracking, blood/body panels, nutrition, lifestyle, dashboard widget
Adam Eivy8636a4619c56
diff --git a/.changelog/v1.9.x.md b/.changelog/v1.9.x.mdnew file mode 100644index 0000000000..9e50a12b1b--- /dev/null+++ b/.changelog/v1.9.x.md@@ -0,0 +1,39 @@+# Release v1.9.x - Changelog++Released: YYYY-MM-DD++## Overview++MeatSpace Phases 2-5: Complete health tracking with alcohol logging, blood/body/epigenetic panels, nutrition dashboard, lifestyle questionnaire, and dashboard death clock widget.++## Features++### MeatSpace Phase 2 — Alcohol Tracking+- **Drink logger** with quick-add common drinks (beer, wine, spirits) and custom entry form (name, oz, ABV, date)+- **Standard drink calculator** widget: interactive oz x ABV helper showing pure alcohol and standard drink equivalents+- **Rolling averages** with 5-minute cache: today's total, 7-day/30-day/all-time daily averages, weekly total+- **NIAAA risk classification**: low/moderate/high based on weekly total vs sex-specific thresholds (male: 14/week, female: 7/week)+- **Alcohol consumption chart**: Recharts BarChart with 7d/30d/90d views, daily limit reference line, zero-fill for missing dates+- **Drink deletion**: Remove individual drink entries from daily logs+- New API endpoints: `GET /api/meatspace/alcohol`, `GET /api/meatspace/alcohol/daily`, `POST /api/meatspace/alcohol/log`, `DELETE /api/meatspace/alcohol/log/:date/:index`+- 14 new tests for standard drink math and rolling average computation++### MeatSpace Phase 3 — Blood & Body+- **Blood test panels** with reference range highlighting (normal/low/high color coding), categorized by Lipids, CBC, Thyroid, Metabolic Panel+- **Body composition chart**: Recharts dual-axis LineChart with weight (lbs) and body fat % over time+- **Epigenetic age dashboard**: Latest biological vs chronological age, pace of aging, organ-specific scores with color-coded status, test history+- **Eye prescription display**: OD/OD spherical, cylinder, axis values with formatted sign prefixes+- Health API functions: `getBloodTests`, `addBloodTest`, `getBodyHistory`, `addBodyEntry`, `getEpigeneticTests`, `addEpigeneticTest`, `getEyeExams`, `addEyeExam`, `getNutritionSummary`, `getDailyNutrition`+- New API endpoints: `GET/POST /api/meatspace/blood`, `GET/POST /api/meatspace/body`, `GET/POST /api/meatspace/epigenetic`, `GET/POST /api/meatspace/eyes`, `GET /api/meatspace/nutrition`, `GET /api/meatspace/nutrition/daily`+- 17 new tests for nutrition averages, mercury stats, body history extraction, merge, and date sorting++### MeatSpace Phase 4 — Nutrition & Lifestyle+- **Nutrition dashboard**: Daily macro averages (calories, fat, sat/trans/poly/mono, carbs, fiber, sugar) with color-coded display+- **Mercury exposure tracking**: Average daily intake with EPA reference dose context, color-coded risk thresholds+- **Recent nutrition table**: Last 7 days of daily macro breakdown+- **Lifestyle questionnaire form**: Smoking status, exercise minutes/week (slider), sleep hours/night (slider), diet quality, stress level, BMI with auto-classification+- **Impact preview panel**: Real-time calculation of each lifestyle factor's effect on life expectancy (years gained/lost)+- Lifestyle saves trigger death clock recalculation via `PUT /api/meatspace/lifestyle`++### MeatSpace Phase 5 — Polish+- **Dashboard death clock widget**: Compact live countdown on main Dashboard with link to MeatSpace overview, shows life expectancy and percent completediff --git a/PLAN.md b/PLAN.mdindex 6ae9d87d26..fb2f253f1f 100644--- a/PLAN.md+++ b/PLAN.md@@ -77,6 +77,8 @@ pm2 logs- [ ] **M34 P5-P7**: Digital Twin - Multi-modal capture, advanced testing, personas- [x] **M42 P4**: Unified Digital Twin Identity System - Identity Tab UI dashboard with completeness header, 5 summary cards, derive actions- [ ] **M42 P5**: Unified Digital Twin Identity System - Cross-Insights Engine. See [Identity System](./docs/features/identity-system.md)+- [x] **M44 P1-P5**: MeatSpace - Health tracker with death clock, LEV 2045 tracker, alcohol logging, blood/body/epigenetic tracking, nutrition, lifestyle questionnaire, TSV import, dashboard widget+- [ ] **M44 P6**: MeatSpace - Genome/Epigenetic Migration from Digital Twin to MeatSpace---diff --git a/client/src/components/DeathClockWidget.jsx b/client/src/components/DeathClockWidget.jsxnew file mode 100644index 0000000000..91fede6fc4--- /dev/null+++ b/client/src/components/DeathClockWidget.jsx@@ -0,0 +1,59 @@+import { useState, useEffect, useCallback } from 'react';+import { Link } from 'react-router-dom';+import { Skull } from 'lucide-react';+import * as api from '../services/api';+import { useDeathClock } from '../hooks/useDeathClock';++export default function DeathClockWidget() {+ const [deathData, setDeathData] = useState(null);+ const [loaded, setLoaded] = useState(false);++ const fetchData = useCallback(async () => {+ const data = await api.getDeathClock().catch(() => null);+ setDeathData(data);+ setLoaded(true);+ }, []);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const countdown = useDeathClock(deathData?.deathDate);++ if (!loaded || deathData?.error || !deathData?.deathDate) return null;++ return (+ <Link+ to="/meatspace/overview"+ className="bg-port-card border border-port-border rounded-xl p-4 h-full block hover:border-gray-600 transition-colors"+ >+ <div className="flex items-center gap-2 mb-3">+ <Skull size={16} className="text-gray-500" />+ <h3 className="text-sm font-semibold text-white">Death Clock</h3>+ </div>+ {countdown && (+ <div className="flex gap-2 text-center">+ <TimeUnit value={countdown.years} label="yr" />+ <TimeUnit value={countdown.months} label="mo" />+ <TimeUnit value={countdown.days} label="d" />+ <TimeUnit value={countdown.hours} label="h" />+ <TimeUnit value={countdown.minutes} label="m" />+ <TimeUnit value={countdown.seconds} label="s" />+ </div>+ )}+ <div className="mt-2 flex justify-between text-xs">+ <span className="text-gray-600">LE: {deathData.lifeExpectancy?.total}y</span>+ <span className="text-gray-600">{deathData.percentComplete}% complete</span>+ </div>+ </Link>+ );+}++function TimeUnit({ value, label }) {+ return (+ <div className="flex-1">+ <div className="text-lg font-mono font-bold text-gray-300">{value}</div>+ <div className="text-xs text-gray-600">{label}</div>+ </div>+ );+}diff --git a/client/src/components/meatspace/AlcoholChart.jsx b/client/src/components/meatspace/AlcoholChart.jsxnew file mode 100644index 0000000000..0c6c306db2--- /dev/null+++ b/client/src/components/meatspace/AlcoholChart.jsx@@ -0,0 +1,125 @@+import { useState, useEffect, useCallback } from 'react';+import {+ BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ReferenceLine+} from 'recharts';+import * as api from '../../services/api';+import BrailleSpinner from '../BrailleSpinner';++const VIEWS = [+ { id: '7d', label: '7 Days', days: 7 },+ { id: '30d', label: '30 Days', days: 30 },+ { id: '90d', label: '90 Days', days: 90 }+];++export default function AlcoholChart({ sex = 'male', onRefreshKey }) {+ const [data, setData] = useState([]);+ const [loading, setLoading] = useState(true);+ const [view, setView] = useState('30d');++ const dailyMax = sex === 'female' ? 1 : 2;++ const fetchData = useCallback(async () => {+ const days = VIEWS.find(v => v.id === view)?.days || 30;+ const from = new Date();+ from.setDate(from.getDate() - days);+ const fromStr = from.toISOString().split('T')[0];+ const toStr = new Date().toISOString().split('T')[0];++ const entries = await api.getDailyAlcohol(fromStr, toStr).catch(() => []);++ // Build chart data with all dates in range (fill zeros)+ const chartData = [];+ const dateMap = {};+ for (const entry of entries) {+ dateMap[entry.date] = entry.alcohol?.standardDrinks || 0;+ }++ const cursor = new Date(from);+ const end = new Date(toStr);+ while (cursor <= end) {+ const dateStr = cursor.toISOString().split('T')[0];+ chartData.push({+ date: dateStr,+ label: `${cursor.getMonth() + 1}/${cursor.getDate()}`,+ drinks: dateMap[dateStr] || 0+ });+ cursor.setDate(cursor.getDate() + 1);+ }++ setData(chartData);+ setLoading(false);+ }, [view]);++ useEffect(() => {+ fetchData();+ }, [fetchData, onRefreshKey]);++ const CustomTooltip = ({ active, payload, label }) => {+ if (!active || !payload?.length) return null;+ const drinks = payload[0].value;+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-2 text-sm">+ <p className="text-gray-400">{label}</p>+ <p className={`font-semibold ${drinks > dailyMax ? 'text-port-error' : 'text-port-accent'}`}>+ {drinks} std drinks+ </p>+ </div>+ );+ };++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center justify-between mb-4">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Daily Consumption+ </h3>+ <div className="flex gap-1">+ {VIEWS.map(v => (+ <button+ key={v.id}+ onClick={() => setView(v.id)}+ className={`px-2 py-1 text-xs rounded transition-colors ${+ view === v.id+ ? 'bg-port-accent/10 text-port-accent'+ : 'text-gray-500 hover:text-gray-300'+ }`}+ >+ {v.label}+ </button>+ ))}+ </div>+ </div>++ {loading ? (+ <div className="flex justify-center py-8">+ <BrailleSpinner text="Loading chart" />+ </div>+ ) : (+ <ResponsiveContainer width="100%" height={250}>+ <BarChart data={data} margin={{ top: 5, right: 5, bottom: 5, left: 0 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />+ <XAxis+ dataKey="label"+ tick={{ fill: '#6b7280', fontSize: 11 }}+ interval={view === '7d' ? 0 : view === '30d' ? 2 : 6}+ />+ <YAxis tick={{ fill: '#6b7280', fontSize: 11 }} />+ <Tooltip content={<CustomTooltip />} />+ <ReferenceLine+ y={dailyMax}+ stroke="#f59e0b"+ strokeDasharray="5 5"+ label={{ value: 'Daily limit', fill: '#f59e0b', fontSize: 10, position: 'right' }}+ />+ <Bar+ dataKey="drinks"+ radius={[2, 2, 0, 0]}+ fill="#3b82f6"+ maxBarSize={view === '7d' ? 40 : view === '30d' ? 16 : 8}+ />+ </BarChart>+ </ResponsiveContainer>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/BloodTestCard.jsx b/client/src/components/meatspace/BloodTestCard.jsxnew file mode 100644index 0000000000..202aeb9186--- /dev/null+++ b/client/src/components/meatspace/BloodTestCard.jsx@@ -0,0 +1,59 @@+import { REFERENCE_RANGES, getBloodValueStatus, STATUS_COLORS } from './constants';++export default function BloodTestCard({ test }) {+ if (!test) return null;++ const { date, ...values } = test;++ // Group values by category+ const categories = {};+ for (const [key, val] of Object.entries(values)) {+ if (val == null || typeof val !== 'number') continue;+ const range = REFERENCE_RANGES[key];+ const status = getBloodValueStatus(val, range);+ const category = range ? getCategoryForKey(key) : 'Other';+ if (!categories[category]) categories[category] = [];+ categories[category].push({+ key,+ value: val,+ label: range?.label || key,+ unit: range?.unit || '',+ status,+ range+ });+ }++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <h4 className="text-sm font-medium text-gray-300 mb-3">{date}</h4>+ <div className="space-y-3">+ {Object.entries(categories).map(([category, items]) => (+ <div key={category}>+ <h5 className="text-xs font-medium text-gray-500 uppercase mb-1">{category}</h5>+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2">+ {items.map(item => (+ <div key={item.key} className="flex items-baseline justify-between gap-2 px-2 py-1 rounded bg-port-bg/50">+ <span className="text-xs text-gray-400 truncate">{item.label}</span>+ <span className={`text-sm font-mono font-medium ${STATUS_COLORS[item.status]}`}>+ {item.value}+ {item.unit && <span className="text-xs text-gray-600 ml-0.5">{item.unit}</span>}+ </span>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ </div>+ );+}++function getCategoryForKey(key) {+ const lipids = ['cholesterol', 'hdl', 'ldl', 'triglycerides'];+ const cbc = ['wbc', 'rbc', 'hemoglobin', 'hematocrit', 'platelets'];+ const thyroid = ['tsh'];+ if (lipids.includes(key)) return 'Lipids';+ if (cbc.includes(key)) return 'CBC';+ if (thyroid.includes(key)) return 'Thyroid';+ return 'Metabolic Panel';+}diff --git a/client/src/components/meatspace/BodyCompChart.jsx b/client/src/components/meatspace/BodyCompChart.jsxnew file mode 100644index 0000000000..e27be2cc4e--- /dev/null+++ b/client/src/components/meatspace/BodyCompChart.jsx@@ -0,0 +1,119 @@+import { useState, useEffect, useCallback } from 'react';+import {+ LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend+} from 'recharts';+import * as api from '../../services/api';+import BrailleSpinner from '../BrailleSpinner';++export default function BodyCompChart() {+ const [data, setData] = useState([]);+ const [loading, setLoading] = useState(true);++ const fetchData = useCallback(async () => {+ const history = await api.getBodyHistory().catch(() => []);+ const chartData = history.map(entry => ({+ date: entry.date,+ label: `${new Date(entry.date).getMonth() + 1}/${new Date(entry.date).getDate()}`,+ weight: entry.weightLbs || null,+ fatPct: entry.fatPct || null,+ musclePct: entry.musclePct || null+ })).filter(d => d.weight !== null);+ setData(chartData);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ if (loading) {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex justify-center py-8">+ <BrailleSpinner text="Loading chart" />+ </div>+ </div>+ );+ }++ if (data.length === 0) {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-2">Body Composition</h3>+ <p className="text-gray-500 text-sm">No body composition data. Import your health spreadsheet to see trends.</p>+ </div>+ );+ }++ const CustomTooltip = ({ active, payload, label }) => {+ if (!active || !payload?.length) return null;+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-2 text-sm">+ <p className="text-gray-400 mb-1">{label}</p>+ {payload.map(p => (+ <p key={p.dataKey} style={{ color: p.color }}>+ {p.name}: {p.value}{p.dataKey === 'weight' ? ' lbs' : '%'}+ </p>+ ))}+ </div>+ );+ };++ // Determine Y axes+ const hasBodyFat = data.some(d => d.fatPct);++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">+ Body Composition Over Time+ </h3>+ <ResponsiveContainer width="100%" height={300}>+ <LineChart data={data} margin={{ top: 5, right: 5, bottom: 5, left: 0 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />+ <XAxis+ dataKey="label"+ tick={{ fill: '#6b7280', fontSize: 11 }}+ interval={Math.max(0, Math.floor(data.length / 12))}+ />+ <YAxis+ yAxisId="weight"+ tick={{ fill: '#6b7280', fontSize: 11 }}+ domain={['dataMin - 5', 'dataMax + 5']}+ />+ {hasBodyFat && (+ <YAxis+ yAxisId="pct"+ orientation="right"+ tick={{ fill: '#6b7280', fontSize: 11 }}+ domain={[0, 50]}+ />+ )}+ <Tooltip content={<CustomTooltip />} />+ <Legend />+ <Line+ yAxisId="weight"+ type="monotone"+ dataKey="weight"+ name="Weight (lbs)"+ stroke="#3b82f6"+ dot={false}+ strokeWidth={2}+ connectNulls+ />+ {hasBodyFat && (+ <Line+ yAxisId="pct"+ type="monotone"+ dataKey="fatPct"+ name="Body Fat %"+ stroke="#ef4444"+ dot={false}+ strokeWidth={2}+ connectNulls+ />+ )}+ </LineChart>+ </ResponsiveContainer>+ </div>+ );+}diff --git a/client/src/components/meatspace/StandardDrinkCalculator.jsx b/client/src/components/meatspace/StandardDrinkCalculator.jsxnew file mode 100644index 0000000000..4e5789177d--- /dev/null+++ b/client/src/components/meatspace/StandardDrinkCalculator.jsx@@ -0,0 +1,61 @@+import { useState } from 'react';+import { Calculator } from 'lucide-react';++export default function StandardDrinkCalculator() {+ const [oz, setOz] = useState('');+ const [abv, setAbv] = useState('');++ const pureAlcohol = oz && abv ? (parseFloat(oz) * parseFloat(abv) / 100) : 0;+ const standardDrinks = pureAlcohol > 0 ? Math.round((pureAlcohol / 0.6) * 100) / 100 : 0;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <div className="flex items-center gap-2 mb-3">+ <Calculator size={16} className="text-gray-400" />+ <h4 className="text-xs font-medium text-gray-400 uppercase tracking-wider">+ Standard Drink Calculator+ </h4>+ </div>+ <div className="flex items-end gap-3">+ <div className="flex-1">+ <label className="text-xs text-gray-500 block mb-1">Oz</label>+ <input+ type="number"+ step="0.1"+ min="0"+ value={oz}+ onChange={e => setOz(e.target.value)}+ placeholder="12"+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white placeholder-gray-600"+ />+ </div>+ <span className="text-gray-500 pb-1.5">@</span>+ <div className="flex-1">+ <label className="text-xs text-gray-500 block mb-1">ABV %</label>+ <input+ type="number"+ step="0.1"+ min="0"+ max="100"+ value={abv}+ onChange={e => setAbv(e.target.value)}+ placeholder="5"+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white placeholder-gray-600"+ />+ </div>+ <span className="text-gray-500 pb-1.5">=</span>+ <div className="text-center pb-1">+ <span className="text-xs text-gray-500 block">Std drinks</span>+ <span className={`text-lg font-bold ${standardDrinks > 2 ? 'text-port-error' : standardDrinks > 0 ? 'text-port-accent' : 'text-gray-500'}`}>+ {standardDrinks || '—'}+ </span>+ </div>+ </div>+ {pureAlcohol > 0 && (+ <p className="text-xs text-gray-500 mt-2">+ {Math.round(pureAlcohol * 100) / 100} oz pure alcohol ({Math.round(pureAlcohol * 29.5735 * 100) / 100} mL)+ </p>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/tabs/AlcoholTab.jsx b/client/src/components/meatspace/tabs/AlcoholTab.jsxindex d34f8e89ab..718ffbd39a 100644--- a/client/src/components/meatspace/tabs/AlcoholTab.jsx+++ b/client/src/components/meatspace/tabs/AlcoholTab.jsx@@ -1,16 +1,290 @@-import { Beer } from 'lucide-react';+import { useState, useEffect, useCallback } from 'react';+import { Beer, Plus, Trash2, AlertTriangle, TrendingDown, TrendingUp } from 'lucide-react';+import * as api from '../../../services/api';+import BrailleSpinner from '../../BrailleSpinner';+import AlcoholChart from '../AlcoholChart';+import StandardDrinkCalculator from '../StandardDrinkCalculator';++const COMMON_DRINKS = [+ { name: 'Beer (12oz)', oz: 12, abv: 5 },+ { name: 'IPA (16oz)', oz: 16, abv: 6.5 },+ { name: 'Wine (5oz)', oz: 5, abv: 12 },+ { name: 'Spirit (1.5oz)', oz: 1.5, abv: 40 },+ { name: 'Cocktail (6oz)', oz: 6, abv: 15 },+ { name: 'Hard Seltzer (12oz)', oz: 12, abv: 5 },+ { name: 'Guinness (14.9oz)', oz: 14.9, abv: 4.2 }+];++const RISK_COLORS = {+ low: 'text-port-success',+ moderate: 'text-port-warning',+ high: 'text-port-error'+};++const RISK_BG = {+ low: 'bg-port-success/10 border-port-success/30',+ moderate: 'bg-port-warning/10 border-port-warning/30',+ high: 'bg-port-error/10 border-port-error/30'+};export default function AlcoholTab() {+ const [summary, setSummary] = useState(null);+ const [loading, setLoading] = useState(true);+ const [logging, setLogging] = useState(false);+ const [refreshKey, setRefreshKey] = useState(0);++ // Form state+ const [name, setName] = useState('');+ const [oz, setOz] = useState('');+ const [abv, setAbv] = useState('');+ const [count, setCount] = useState(1);+ const [date, setDate] = useState('');++ const fetchSummary = useCallback(async () => {+ const data = await api.getAlcoholSummary().catch(() => null);+ setSummary(data);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchSummary();+ }, [fetchSummary, refreshKey]);++ const handleQuickAdd = async (drink) => {+ setLogging(true);+ await api.logAlcoholDrink({+ name: drink.name,+ oz: drink.oz,+ abv: drink.abv,+ count: 1,+ date: date || undefined+ }).catch(() => null);+ setLogging(false);+ setRefreshKey(k => k + 1);+ };++ const handleCustomAdd = async (e) => {+ e.preventDefault();+ if (!oz || !abv) return;+ setLogging(true);+ await api.logAlcoholDrink({+ name: name || '',+ oz: parseFloat(oz),+ abv: parseFloat(abv),+ count: count || 1,+ date: date || undefined+ }).catch(() => null);+ setLogging(false);+ setName('');+ setOz('');+ setAbv('');+ setCount(1);+ setRefreshKey(k => k + 1);+ };++ const handleRemove = async (entryDate, index) => {+ await api.removeAlcoholDrink(entryDate, index).catch(() => null);+ setRefreshKey(k => k + 1);+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <BrailleSpinner text="Loading" />+ </div>+ );+ }+return (- <div className="bg-port-card border border-port-border rounded-xl p-6">- <div className="flex items-center gap-2 mb-4">- <Beer size={18} className="text-port-accent" />- <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Alcohol Tracking</h3>+ <div className="space-y-6">+ {/* Rolling Averages Summary */}+ {summary && (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center justify-between mb-4">+ <div className="flex items-center gap-2">+ <Beer size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Alcohol Summary+ </h3>+ </div>+ <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border ${RISK_BG[summary.riskLevel]}`}>+ {summary.riskLevel === 'high' && <AlertTriangle size={12} />}+ {summary.riskLevel === 'low' && <TrendingDown size={12} />}+ {summary.riskLevel === 'moderate' && <TrendingUp size={12} />}+ <span className={RISK_COLORS[summary.riskLevel]}>+ {summary.riskLevel === 'low' ? 'Low Risk' : summary.riskLevel === 'moderate' ? 'Moderate Risk' : 'High Risk'}+ </span>+ </span>+ </div>++ <div className="grid grid-cols-2 md:grid-cols-5 gap-4">+ <div>+ <span className="text-xs text-gray-500">Today</span>+ <p className={`text-2xl font-bold ${summary.today > summary.thresholds.dailyMax ? 'text-port-error' : 'text-white'}`}>+ {summary.today}+ </p>+ <span className="text-xs text-gray-600">/ {summary.thresholds.dailyMax} max</span>+ </div>+ <div>+ <span className="text-xs text-gray-500">7-Day Avg</span>+ <p className="text-2xl font-bold text-white">{summary.avg7day}</p>+ <span className="text-xs text-gray-600">per day</span>+ </div>+ <div>+ <span className="text-xs text-gray-500">30-Day Avg</span>+ <p className="text-2xl font-bold text-white">{summary.avg30day}</p>+ <span className="text-xs text-gray-600">per day</span>+ </div>+ <div>+ <span className="text-xs text-gray-500">Weekly Total</span>+ <p className={`text-2xl font-bold ${summary.weeklyTotal > summary.thresholds.weeklyMax ? 'text-port-error' : 'text-white'}`}>+ {summary.weeklyTotal}+ </p>+ <span className="text-xs text-gray-600">/ {summary.thresholds.weeklyMax} max</span>+ </div>+ <div>+ <span className="text-xs text-gray-500">All-Time Avg</span>+ <p className="text-2xl font-bold text-gray-300">{summary.allTimeAvg}</p>+ <span className="text-xs text-gray-600">per day</span>+ </div>+ </div>+ </div>+ )}++ {/* Consumption Chart */}+ <AlcoholChart sex={summary?.sex} onRefreshKey={refreshKey} />++ {/* Log a Drink */}+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">Log a Drink</h3>++ {/* Quick-add buttons */}+ <div className="flex flex-wrap gap-2 mb-4">+ {COMMON_DRINKS.map(drink => (+ <button+ key={drink.name}+ onClick={() => handleQuickAdd(drink)}+ disabled={logging}+ className="flex items-center gap-1 px-3 py-1.5 text-xs bg-port-border/50 text-gray-300 rounded-lg hover:bg-port-accent/10 hover:text-port-accent transition-colors disabled:opacity-50"+ >+ <Plus size={12} />+ {drink.name}+ </button>+ ))}+ </div>++ {/* Custom entry form */}+ <form onSubmit={handleCustomAdd} className="flex flex-wrap items-end gap-3">+ <div className="flex-1 min-w-[120px]">+ <label className="text-xs text-gray-500 block mb-1">Name (optional)</label>+ <input+ type="text"+ value={name}+ onChange={e => setName(e.target.value)}+ placeholder="e.g., Hazy IPA"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-600"+ />+ </div>+ <div className="w-20">+ <label className="text-xs text-gray-500 block mb-1">Oz</label>+ <input+ type="number"+ step="0.1"+ min="0.1"+ value={oz}+ onChange={e => setOz(e.target.value)}+ required+ placeholder="12"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-600"+ />+ </div>+ <div className="w-20">+ <label className="text-xs text-gray-500 block mb-1">ABV %</label>+ <input+ type="number"+ step="0.1"+ min="0"+ max="100"+ value={abv}+ onChange={e => setAbv(e.target.value)}+ required+ placeholder="5"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-600"+ />+ </div>+ <div className="w-16">+ <label className="text-xs text-gray-500 block mb-1">Count</label>+ <input+ type="number"+ min="1"+ max="20"+ value={count}+ onChange={e => setCount(parseInt(e.target.value) || 1)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white"+ />+ </div>+ <div className="w-36">+ <label className="text-xs text-gray-500 block mb-1">Date</label>+ <input+ type="date"+ value={date}+ onChange={e => setDate(e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white"+ />+ </div>+ <button+ type="submit"+ disabled={logging || !oz || !abv}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50 transition-colors"+ >+ {logging ? <BrailleSpinner /> : <Plus size={16} />}+ Log+ </button>+ </form></div>- <p className="text-gray-500">- Drink logger with rolling averages, consumption charts, and NIAAA risk thresholds.- </p>- <p className="text-sm text-gray-600 mt-2">Coming in Phase 2.</p>++ {/* Recent Drinks */}+ {summary?.recentEntries?.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">+ Recent Drinks (7 days)+ </h3>+ <div className="space-y-3">+ {summary.recentEntries.map(entry => (+ <div key={entry.date} className="border border-port-border rounded-lg p-3">+ <div className="flex items-center justify-between mb-2">+ <span className="text-sm font-medium text-gray-300">{entry.date}</span>+ <span className={`text-sm font-bold ${+ entry.alcohol.standardDrinks > (summary.thresholds?.dailyMax || 2) ? 'text-port-error' : 'text-port-accent'+ }`}>+ {entry.alcohol.standardDrinks} std drinks+ </span>+ </div>+ <div className="space-y-1">+ {entry.alcohol.drinks.map((drink, idx) => (+ <div key={idx} className="flex items-center justify-between text-xs">+ <span className="text-gray-400">+ {drink.name || 'Unnamed'} — {drink.oz}oz @ {drink.abv}%+ {drink.count > 1 && ` (x${drink.count})`}+ </span>+ <button+ onClick={() => handleRemove(entry.date, idx)}+ className="text-gray-600 hover:text-port-error transition-colors p-1"+ title="Remove drink"+ >+ <Trash2 size={12} />+ </button>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Standard Drink Calculator */}+ <StandardDrinkCalculator /></div>);}diff --git a/client/src/components/meatspace/tabs/BloodTab.jsx b/client/src/components/meatspace/tabs/BloodTab.jsxindex 38faa72cf2..b7c5c98a60 100644--- a/client/src/components/meatspace/tabs/BloodTab.jsx+++ b/client/src/components/meatspace/tabs/BloodTab.jsx@@ -1,17 +1,210 @@-import { HeartPulse } from 'lucide-react';+import { useState, useEffect, useCallback } from 'react';+import { HeartPulse, Eye, Dna, Scale } from 'lucide-react';+import * as api from '../../../services/api';+import BrailleSpinner from '../../BrailleSpinner';+import BloodTestCard from '../BloodTestCard';+import BodyCompChart from '../BodyCompChart';export default function BloodTab() {+ const [bloodData, setBloodData] = useState(null);+ const [epigeneticData, setEpigeneticData] = useState(null);+ const [eyeData, setEyeData] = useState(null);+ const [loading, setLoading] = useState(true);++ const fetchData = useCallback(async () => {+ const [blood, epigenetic, eyes] = await Promise.all([+ api.getBloodTests().catch(() => ({ tests: [] })),+ api.getEpigeneticTests().catch(() => ({ tests: [] })),+ api.getEyeExams().catch(() => ({ exams: [] }))+ ]);+ setBloodData(blood);+ setEpigeneticData(epigenetic);+ setEyeData(eyes);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ if (loading) {+ return (+ <div className="flex justify-center py-12">+ <BrailleSpinner text="Loading health data" />+ </div>+ );+ }++ const bloodTests = bloodData?.tests || [];+ const epigeneticTests = epigeneticData?.tests || [];+ const eyeExams = eyeData?.exams || [];+ const latestEpigenetic = epigeneticTests[epigeneticTests.length - 1];+return (- <div className="bg-port-card border border-port-border rounded-xl p-6">- <div className="flex items-center gap-2 mb-4">- <HeartPulse size={18} className="text-port-accent" />- <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Blood & Body</h3>+ <div className="space-y-6">+ {/* Epigenetic Age Summary */}+ {latestEpigenetic && (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <Dna size={18} className="text-purple-400" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Epigenetic Age</h3>+ </div>+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">+ <div>+ <p className="text-xs text-gray-500 uppercase">Chronological</p>+ <p className="text-2xl font-mono font-bold text-gray-300">{latestEpigenetic.chronologicalAge}</p>+ </div>+ <div>+ <p className="text-xs text-gray-500 uppercase">Biological</p>+ <p className={`text-2xl font-mono font-bold ${+ latestEpigenetic.biologicalAge < latestEpigenetic.chronologicalAge+ ? 'text-port-success' : 'text-port-error'+ }`}>+ {latestEpigenetic.biologicalAge}+ </p>+ </div>+ <div>+ <p className="text-xs text-gray-500 uppercase">Pace of Aging</p>+ <p className={`text-2xl font-mono font-bold ${+ latestEpigenetic.paceOfAging < 1 ? 'text-port-success' : 'text-port-error'+ }`}>+ {latestEpigenetic.paceOfAging}+ </p>+ </div>+ <div>+ <p className="text-xs text-gray-500 uppercase">Test Date</p>+ <p className="text-lg font-mono text-gray-400">{latestEpigenetic.date}</p>+ </div>+ </div>++ {/* Organ Scores */}+ {latestEpigenetic.organScores && (+ <div className="mt-4 pt-4 border-t border-port-border">+ <p className="text-xs text-gray-500 uppercase mb-2">Organ Scores (biological age)</p>+ <div className="grid grid-cols-3 md:grid-cols-5 gap-2">+ {Object.entries(latestEpigenetic.organScores).map(([organ, age]) => (+ <div key={organ} className="flex items-baseline justify-between gap-2 px-2 py-1 rounded bg-port-bg/50">+ <span className="text-xs text-gray-400 capitalize">{organ}</span>+ <span className={`text-sm font-mono font-medium ${+ age < latestEpigenetic.chronologicalAge ? 'text-port-success' : 'text-port-error'+ }`}>+ {age}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* History */}+ {epigeneticTests.length > 1 && (+ <div className="mt-4 pt-4 border-t border-port-border">+ <p className="text-xs text-gray-500 uppercase mb-2">History</p>+ <div className="space-y-1">+ {epigeneticTests.map((test, i) => (+ <div key={i} className="flex items-center gap-4 text-sm">+ <span className="text-gray-500 font-mono w-24">{test.date}</span>+ <span className="text-gray-400">Bio: {test.biologicalAge}</span>+ <span className="text-gray-400">Pace: {test.paceOfAging}</span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ )}++ {/* Body Composition Chart */}+ <div>+ <div className="flex items-center gap-2 mb-3">+ <Scale size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Body Composition</h3>+ </div>+ <BodyCompChart />+ </div>++ {/* Blood Tests */}+ <div>+ <div className="flex items-center gap-2 mb-3">+ <HeartPulse size={18} className="text-red-400" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Blood Tests ({bloodTests.length})+ </h3>+ </div>+ {bloodTests.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <p className="text-gray-500 text-sm">No blood test data. Import your health spreadsheet or add tests manually.</p>+ </div>+ ) : (+ <div className="space-y-4">+ {[...bloodTests].reverse().map((test, i) => (+ <BloodTestCard key={i} test={test} />+ ))}+ </div>+ )}+ </div>++ {/* Eye Exams */}+ <div>+ <div className="flex items-center gap-2 mb-3">+ <Eye size={18} className="text-blue-400" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Eye Prescriptions ({eyeExams.length})+ </h3>+ </div>+ {eyeExams.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <p className="text-gray-500 text-sm">No eye exam data. Import your health spreadsheet or add exams manually.</p>+ </div>+ ) : (+ <div className="space-y-3">+ {[...eyeExams].reverse().map((exam, i) => (+ <div key={i} className="bg-port-card border border-port-border rounded-xl p-4">+ <h4 className="text-sm font-medium text-gray-300 mb-3">{exam.date}</h4>+ <div className="grid grid-cols-2 gap-4">+ {['right', 'left'].map(side => {+ const eye = exam[side];+ if (!eye) return null;+ return (+ <div key={side}>+ <p className="text-xs font-medium text-gray-500 uppercase mb-1">+ {side === 'right' ? 'OD (Right)' : 'OS (Left)'}+ </p>+ <div className="grid grid-cols-3 gap-2 text-sm">+ {eye.sphere != null && (+ <div>+ <span className="text-xs text-gray-600">SPH</span>+ <p className="font-mono text-gray-300">{eye.sphere > 0 ? '+' : ''}{eye.sphere}</p>+ </div>+ )}+ {eye.cylinder != null && (+ <div>+ <span className="text-xs text-gray-600">CYL</span>+ <p className="font-mono text-gray-300">{eye.cylinder > 0 ? '+' : ''}{eye.cylinder}</p>+ </div>+ )}+ {eye.axis != null && (+ <div>+ <span className="text-xs text-gray-600">AXIS</span>+ <p className="font-mono text-gray-300">{eye.axis}°</p>+ </div>+ )}+ </div>+ </div>+ );+ })}+ </div>+ {exam.add != null && (+ <div className="mt-2 pt-2 border-t border-port-border">+ <span className="text-xs text-gray-600">ADD</span>+ <span className="font-mono text-gray-300 ml-2">+{exam.add}</span>+ </div>+ )}+ </div>+ ))}+ </div>+ )}</div>- <p className="text-gray-500">- Blood test panels with reference range highlighting, body composition charts,- epigenetic age tracking, and eye prescription history.- </p>- <p className="text-sm text-gray-600 mt-2">Coming in Phase 3.</p></div>);}diff --git a/client/src/components/meatspace/tabs/LifestyleTab.jsx b/client/src/components/meatspace/tabs/LifestyleTab.jsxindex 3223082a57..b00afe162e 100644--- a/client/src/components/meatspace/tabs/LifestyleTab.jsx+++ b/client/src/components/meatspace/tabs/LifestyleTab.jsx@@ -1,17 +1,298 @@-import { ClipboardList } from 'lucide-react';+import { useState, useEffect, useCallback } from 'react';+import { ClipboardList, Save } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../../services/api';+import BrailleSpinner from '../../BrailleSpinner';++const SMOKING_OPTIONS = [+ { value: 'never', label: 'Never' },+ { value: 'former', label: 'Former' },+ { value: 'current', label: 'Current' }+];++const DIET_OPTIONS = [+ { value: 'excellent', label: 'Excellent' },+ { value: 'good', label: 'Good' },+ { value: 'fair', label: 'Fair' },+ { value: 'poor', label: 'Poor' }+];++const STRESS_OPTIONS = [+ { value: 'low', label: 'Low' },+ { value: 'moderate', label: 'Moderate' },+ { value: 'high', label: 'High' }+];export default function LifestyleTab() {+ const [config, setConfig] = useState(null);+ const [lifestyle, setLifestyle] = useState(null);+ const [saving, setSaving] = useState(false);+ const [loading, setLoading] = useState(true);++ const fetchData = useCallback(async () => {+ const data = await api.getMeatspaceConfig().catch(() => null);+ setConfig(data);+ setLifestyle(data?.lifestyle || {+ smokingStatus: 'never',+ exerciseMinutesPerWeek: 150,+ sleepHoursPerNight: 7.5,+ dietQuality: 'good',+ stressLevel: 'moderate',+ bmi: null,+ chronicConditions: []+ });+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ const handleSave = async () => {+ setSaving(true);+ const result = await api.updateMeatspaceLifestyle(lifestyle).catch(() => null);+ setSaving(false);+ if (result) {+ setConfig(result);+ toast.success('Lifestyle updated — death clock recalculated');+ }+ };++ const updateField = (field, value) => {+ setLifestyle(prev => ({ ...prev, [field]: value }));+ };++ if (loading) {+ return (+ <div className="flex justify-center py-12">+ <BrailleSpinner text="Loading lifestyle data" />+ </div>+ );+ }+return (- <div className="bg-port-card border border-port-border rounded-xl p-6">- <div className="flex items-center gap-2 mb-4">- <ClipboardList size={18} className="text-port-accent" />- <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Lifestyle Questionnaire</h3>+ <div className="space-y-6">+ {/* Sex */}+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <ClipboardList size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Profile</h3>+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div>+ <label className="block text-xs text-gray-500 uppercase mb-1">Biological Sex</label>+ <p className="text-lg font-mono text-gray-300 capitalize">+ {config?.sex || 'Unknown'}+ {config?.sexSource && (+ <span className="text-xs text-gray-600 ml-2">({config.sexSource})</span>+ )}+ </p>+ </div>+ </div>+ </div>++ {/* Lifestyle Questionnaire */}+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center justify-between mb-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Lifestyle Questionnaire</h3>+ <button+ onClick={handleSave}+ disabled={saving}+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50"+ >+ <Save size={14} />+ {saving ? 'Saving...' : 'Save'}+ </button>+ </div>++ <div className="space-y-5">+ {/* Smoking */}+ <FieldGroup label="Smoking Status">+ <div className="flex gap-2">+ {SMOKING_OPTIONS.map(opt => (+ <button+ key={opt.value}+ onClick={() => updateField('smokingStatus', opt.value)}+ className={`px-3 py-1.5 text-sm rounded-lg border ${+ lifestyle?.smokingStatus === opt.value+ ? 'border-port-accent bg-port-accent/20 text-port-accent'+ : 'border-port-border text-gray-400 hover:border-gray-500'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </FieldGroup>++ {/* Exercise */}+ <FieldGroup label="Exercise (minutes/week)">+ <div className="flex items-center gap-3">+ <input+ type="range"+ min="0"+ max="600"+ step="15"+ value={lifestyle?.exerciseMinutesPerWeek ?? 150}+ onChange={e => updateField('exerciseMinutesPerWeek', parseInt(e.target.value, 10))}+ className="flex-1 accent-port-accent"+ />+ <span className="text-lg font-mono text-gray-300 w-16 text-right">+ {lifestyle?.exerciseMinutesPerWeek ?? 150}+ </span>+ </div>+ <p className="text-xs text-gray-600 mt-1">+ WHO recommends 150+ min/week moderate or 75+ min/week vigorous activity+ </p>+ </FieldGroup>++ {/* Sleep */}+ <FieldGroup label="Sleep (hours/night)">+ <div className="flex items-center gap-3">+ <input+ type="range"+ min="3"+ max="12"+ step="0.5"+ value={lifestyle?.sleepHoursPerNight ?? 7.5}+ onChange={e => updateField('sleepHoursPerNight', parseFloat(e.target.value))}+ className="flex-1 accent-port-accent"+ />+ <span className="text-lg font-mono text-gray-300 w-12 text-right">+ {lifestyle?.sleepHoursPerNight ?? 7.5}+ </span>+ </div>+ <p className="text-xs text-gray-600 mt-1">+ Optimal range: 7-9 hours for longevity+ </p>+ </FieldGroup>++ {/* Diet Quality */}+ <FieldGroup label="Diet Quality">+ <div className="flex gap-2">+ {DIET_OPTIONS.map(opt => (+ <button+ key={opt.value}+ onClick={() => updateField('dietQuality', opt.value)}+ className={`px-3 py-1.5 text-sm rounded-lg border ${+ lifestyle?.dietQuality === opt.value+ ? 'border-port-accent bg-port-accent/20 text-port-accent'+ : 'border-port-border text-gray-400 hover:border-gray-500'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </FieldGroup>++ {/* Stress Level */}+ <FieldGroup label="Stress Level">+ <div className="flex gap-2">+ {STRESS_OPTIONS.map(opt => (+ <button+ key={opt.value}+ onClick={() => updateField('stressLevel', opt.value)}+ className={`px-3 py-1.5 text-sm rounded-lg border ${+ lifestyle?.stressLevel === opt.value+ ? 'border-port-accent bg-port-accent/20 text-port-accent'+ : 'border-port-border text-gray-400 hover:border-gray-500'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </FieldGroup>++ {/* BMI */}+ <FieldGroup label="BMI (auto-calculated from body data when available)">+ <div className="flex items-center gap-3">+ <input+ type="number"+ min="10"+ max="80"+ step="0.1"+ value={lifestyle?.bmi ?? ''}+ onChange={e => updateField('bmi', e.target.value ? parseFloat(e.target.value) : null)}+ placeholder="e.g. 22.5"+ className="w-32 px-3 py-1.5 text-sm font-mono bg-port-bg border border-port-border rounded-lg text-gray-300 placeholder:text-gray-600"+ />+ {lifestyle?.bmi != null && (+ <span className={`text-sm font-medium ${+ lifestyle.bmi >= 18.5 && lifestyle.bmi < 25 ? 'text-port-success' :+ lifestyle.bmi >= 25 && lifestyle.bmi < 30 ? 'text-port-warning' :+ 'text-port-error'+ }`}>+ {lifestyle.bmi < 18.5 ? 'Underweight' :+ lifestyle.bmi < 25 ? 'Normal' :+ lifestyle.bmi < 30 ? 'Overweight' : 'Obese'}+ </span>+ )}+ </div>+ </FieldGroup>+ </div>+ </div>++ {/* Impact Preview */}+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">Impact on Life Expectancy</h3>+ <p className="text-xs text-gray-600 mb-3">+ Changes to lifestyle factors are immediately reflected in your death clock calculation when you save.+ </p>+ <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-sm">+ <ImpactItem+ label="Smoking"+ value={lifestyle?.smokingStatus}+ impact={lifestyle?.smokingStatus === 'never' ? '+0' :+ lifestyle?.smokingStatus === 'former' ? '-2' : '-10'}+ />+ <ImpactItem+ label="Exercise"+ value={`${lifestyle?.exerciseMinutesPerWeek ?? 150} min`}+ impact={(lifestyle?.exerciseMinutesPerWeek ?? 150) > 150 ? '+2' :+ (lifestyle?.exerciseMinutesPerWeek ?? 150) >= 75 ? '+0.5' : '-2'}+ />+ <ImpactItem+ label="Sleep"+ value={`${lifestyle?.sleepHoursPerNight ?? 7.5}h`}+ impact={(lifestyle?.sleepHoursPerNight ?? 7.5) >= 7 && (lifestyle?.sleepHoursPerNight ?? 7.5) <= 9 ? '+1' :+ (lifestyle?.sleepHoursPerNight ?? 7.5) >= 6 ? '+0' : '-1.5'}+ />+ <ImpactItem+ label="Diet"+ value={lifestyle?.dietQuality}+ impact={lifestyle?.dietQuality === 'excellent' ? '+2' :+ lifestyle?.dietQuality === 'good' ? '+0.5' :+ lifestyle?.dietQuality === 'fair' ? '+0' : '-3'}+ />+ </div></div>- <p className="text-gray-500">- Smoking, drinking, exercise, sleep, diet quality, stress level, and BMI inputs.- Updates feed into death clock calculation.+ </div>+ );+}++function FieldGroup({ label, children }) {+ return (+ <div>+ <label className="block text-xs text-gray-500 uppercase mb-2">{label}</label>+ {children}+ </div>+ );+}++function ImpactItem({ label, value, impact }) {+ const isPositive = impact.startsWith('+') && impact !== '+0';+ const isNegative = impact.startsWith('-');+ return (+ <div className="bg-port-bg/50 rounded-lg px-3 py-2">+ <p className="text-xs text-gray-500">{label}</p>+ <p className="text-gray-400 capitalize">{value}</p>+ <p className={`font-mono font-medium ${+ isPositive ? 'text-port-success' : isNegative ? 'text-port-error' : 'text-gray-500'+ }`}>+ {impact} yrs</p>- <p className="text-sm text-gray-600 mt-2">Coming in Phase 4.</p></div>);}diff --git a/client/src/components/meatspace/tabs/NutritionTab.jsx b/client/src/components/meatspace/tabs/NutritionTab.jsxindex d6392bf165..02dcc6fb6a 100644--- a/client/src/components/meatspace/tabs/NutritionTab.jsx+++ b/client/src/components/meatspace/tabs/NutritionTab.jsx@@ -1,16 +1,159 @@-import { Apple } from 'lucide-react';+import { useState, useEffect, useCallback } from 'react';+import { Apple, AlertTriangle } from 'lucide-react';+import * as api from '../../../services/api';+import BrailleSpinner from '../../BrailleSpinner';++const MACRO_LABELS = {+ calories: { label: 'Calories', unit: 'kcal', color: 'text-port-accent' },+ fatG: { label: 'Fat', unit: 'g', color: 'text-yellow-400' },+ satFatG: { label: 'Sat Fat', unit: 'g', color: 'text-yellow-500' },+ transFatG: { label: 'Trans Fat', unit: 'g', color: 'text-red-400' },+ polyFatG: { label: 'Poly Fat', unit: 'g', color: 'text-yellow-300' },+ monoFatG: { label: 'Mono Fat', unit: 'g', color: 'text-yellow-300' },+ carbG: { label: 'Carbs', unit: 'g', color: 'text-blue-400' },+ fiberG: { label: 'Fiber', unit: 'g', color: 'text-green-400' },+ sugarG: { label: 'Sugar', unit: 'g', color: 'text-pink-400' }+};export default function NutritionTab() {- return (- <div className="bg-port-card border border-port-border rounded-xl p-6">- <div className="flex items-center gap-2 mb-4">- <Apple size={18} className="text-port-accent" />- <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Nutrition</h3>+ const [summary, setSummary] = useState(null);+ const [loading, setLoading] = useState(true);++ const fetchData = useCallback(async () => {+ const data = await api.getNutritionSummary().catch(() => ({+ totalEntries: 0, averages: null, recentEntries: [], mercury: null+ }));+ setSummary(data);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchData();+ }, [fetchData]);++ if (loading) {+ return (+ <div className="flex justify-center py-12">+ <BrailleSpinner text="Loading nutrition data" />+ </div>+ );+ }++ if (!summary || summary.totalEntries === 0) {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <Apple size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Nutrition</h3>+ </div>+ <p className="text-gray-500 text-sm">No nutrition data. Import your health spreadsheet to see macro trends.</p></div>- <p className="text-gray-500">- Macro tracking, mercury exposure from seafood, daily limits vs actuals.- </p>- <p className="text-sm text-gray-600 mt-2">Coming in Phase 4.</p>+ );+ }++ const { averages, recentEntries, mercury, totalEntries } = summary;++ return (+ <div className="space-y-6">+ {/* Averages Summary */}+ {averages && (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center justify-between mb-4">+ <div className="flex items-center gap-2">+ <Apple size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Daily Averages</h3>+ </div>+ <span className="text-xs text-gray-600">{totalEntries} days tracked</span>+ </div>+ <div className="grid grid-cols-3 md:grid-cols-5 gap-3">+ {Object.entries(MACRO_LABELS).map(([key, meta]) => {+ const val = averages[key];+ if (val == null) return null;+ return (+ <div key={key} className="bg-port-bg/50 rounded-lg px-3 py-2">+ <p className="text-xs text-gray-500">{meta.label}</p>+ <p className={`text-lg font-mono font-bold ${meta.color}`}>+ {Math.round(val)}+ <span className="text-xs text-gray-600 ml-1">{meta.unit}</span>+ </p>+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Mercury Exposure */}+ {mercury?.avgDailyMg != null && (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <AlertTriangle size={18} className="text-port-warning" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Mercury Exposure</h3>+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div className="bg-port-bg/50 rounded-lg px-3 py-2">+ <p className="text-xs text-gray-500">Avg Daily Intake</p>+ <p className={`text-lg font-mono font-bold ${+ mercury.avgDailyMg > 0.05 ? 'text-port-error' :+ mercury.avgDailyMg > 0.02 ? 'text-port-warning' : 'text-port-success'+ }`}>+ {mercury.avgDailyMg.toFixed(3)}+ <span className="text-xs text-gray-600 ml-1">mg</span>+ </p>+ </div>+ <div className="bg-port-bg/50 rounded-lg px-3 py-2">+ <p className="text-xs text-gray-500">Days Tracked</p>+ <p className="text-lg font-mono font-bold text-gray-300">{mercury.daysTracked}</p>+ </div>+ </div>+ <p className="text-xs text-gray-600 mt-3">+ EPA reference dose: 0.045 mg/day (for 70kg adult). FDA recommends limiting high-mercury fish to 2-3 servings/week.+ </p>+ </div>+ )}++ {/* Recent Entries */}+ {recentEntries?.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">Recent Days</h3>+ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="text-xs text-gray-500 uppercase border-b border-port-border">+ <th className="text-left py-2 pr-3">Date</th>+ <th className="text-right py-2 px-2">Cal</th>+ <th className="text-right py-2 px-2">Fat</th>+ <th className="text-right py-2 px-2">Carbs</th>+ <th className="text-right py-2 px-2">Fiber</th>+ <th className="text-right py-2 px-2">Sugar</th>+ </tr>+ </thead>+ <tbody>+ {recentEntries.map(entry => (+ <tr key={entry.date} className="border-b border-port-border/50">+ <td className="py-1.5 pr-3 font-mono text-gray-400">{entry.date}</td>+ <td className="py-1.5 px-2 text-right font-mono text-gray-300">+ {entry.nutrition?.calories ?? '—'}+ </td>+ <td className="py-1.5 px-2 text-right font-mono text-gray-300">+ {entry.nutrition?.fatG ?? '—'}+ </td>+ <td className="py-1.5 px-2 text-right font-mono text-gray-300">+ {entry.nutrition?.carbG ?? '—'}+ </td>+ <td className="py-1.5 px-2 text-right font-mono text-gray-300">+ {entry.nutrition?.fiberG ?? '—'}+ </td>+ <td className="py-1.5 px-2 text-right font-mono text-gray-300">+ {entry.nutrition?.sugarG ?? '—'}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}</div>);}diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex 98584ca741..43101b0291 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -7,6 +7,7 @@ import CosDashboardWidget from '../components/CosDashboardWidget';import GoalProgressWidget from '../components/GoalProgressWidget';import UpcomingTasksWidget from '../components/UpcomingTasksWidget';import DecisionLogWidget from '../components/DecisionLogWidget';+import DeathClockWidget from '../components/DeathClockWidget';import QuickBrainCapture from '../components/QuickBrainCapture';import QuickTaskWidget from '../components/QuickTaskWidget';import * as api from '../services/api';@@ -129,8 +130,9 @@ export default function Dashboard() {</div>{/* Row 4 — Status, stats, decisions */}- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">+ <div className="grid grid-cols-1 lg:grid-cols-4 gap-4"><SystemHealthWidget />+ <DeathClockWidget />{apps.length > 0 && (<div className="bg-port-card border border-port-border rounded-xl p-4 h-full"><h3 className="text-sm font-semibold text-white mb-3">Quick Stats</h3>diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 6fcf48365c..a947410cdd 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1272,10 +1272,51 @@ export const updateMeatspaceLifestyle = (data) => request('/meatspace/lifestyle'});export const getDeathClock = () => request('/meatspace/death-clock');export const getLEV = () => request('/meatspace/lev');+export const getAlcoholSummary = () => request('/meatspace/alcohol');+export const getDailyAlcohol = (from, to) => {+ const params = new URLSearchParams();+ if (from) params.set('from', from);+ if (to) params.set('to', to);+ return request(`/meatspace/alcohol/daily?${params}`);+};+export const logAlcoholDrink = (data) => request('/meatspace/alcohol/log', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const removeAlcoholDrink = (date, index) => request(`/meatspace/alcohol/log/${date}/${index}`, {+ method: 'DELETE'+});export const importMeatspaceTSV = (content) => request('/meatspace/import/tsv', {method: 'POST',body: JSON.stringify({ content })});+export const getBloodTests = () => request('/meatspace/blood');+export const addBloodTest = (data) => request('/meatspace/blood', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const getBodyHistory = () => request('/meatspace/body');+export const addBodyEntry = (data) => request('/meatspace/body', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const getEpigeneticTests = () => request('/meatspace/epigenetic');+export const addEpigeneticTest = (data) => request('/meatspace/epigenetic', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const getEyeExams = () => request('/meatspace/eyes');+export const addEyeExam = (data) => request('/meatspace/eyes', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const getNutritionSummary = () => request('/meatspace/nutrition');+export const getDailyNutrition = (from, to) => {+ const params = new URLSearchParams();+ if (from) params.set('from', from);+ if (to) params.set('to', to);+ return request(`/meatspace/nutrition/daily?${params}`);+};// JIRAexport const getJiraInstances = () => request('/jira/instances');diff --git a/package-lock.json b/package-lock.jsonindex fb266a75b1..100889fee0 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "portos",- "version": "1.9.0",+ "version": "1.10.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos",- "version": "1.9.0",+ "version": "1.10.0","license": "MIT","dependencies": {"express": "^4.21.2",diff --git a/package.json b/package.jsonindex 8005afb266..cfce1b0518 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "1.9.0",+ "version": "1.10.0","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/server/routes/meatspace.js b/server/routes/meatspace.jsindex e8cb4789c5..00d67b5ebf 100644--- a/server/routes/meatspace.js+++ b/server/routes/meatspace.js@@ -4,9 +4,16 @@ import { validateRequest } from '../lib/validation.js';import {configUpdateSchema,lifestyleUpdateSchema,+ drinkLogSchema,+ bloodTestSchema,+ bodyEntrySchema,+ epigeneticTestSchema,+ eyeExamSchema,tsvImportSchema} from '../lib/meatspaceValidation.js';import * as meatspaceService from '../services/meatspace.js';+import * as alcoholService from '../services/meatspaceAlcohol.js';+import * as healthService from '../services/meatspaceHealth.js';import { importTSV } from '../services/meatspaceImport.js';const router = Router();@@ -79,6 +86,153 @@ router.get('/lev', asyncHandler(async (req, res) => {res.json(lev);}));+// =============================================================================+// ALCOHOL+// =============================================================================++/**+ * GET /api/meatspace/alcohol+ * Alcohol summary with rolling averages+ */+router.get('/alcohol', asyncHandler(async (req, res) => {+ const summary = await alcoholService.getAlcoholSummary();+ res.json(summary);+}));++/**+ * GET /api/meatspace/alcohol/daily+ * Daily alcohol entries with optional date range+ */+router.get('/alcohol/daily', asyncHandler(async (req, res) => {+ const entries = await alcoholService.getDailyAlcohol(req.query.from, req.query.to);+ res.json(entries);+}));++/**+ * POST /api/meatspace/alcohol/log+ * Log a drink+ */+router.post('/alcohol/log', asyncHandler(async (req, res) => {+ const data = validateRequest(drinkLogSchema, req.body);+ const result = await alcoholService.logDrink(data);+ res.status(201).json(result);+}));++/**+ * DELETE /api/meatspace/alcohol/log/:date/:index+ * Remove a specific drink entry+ */+router.delete('/alcohol/log/:date/:index', asyncHandler(async (req, res) => {+ const { date, index } = req.params;+ const removed = await alcoholService.removeDrink(date, parseInt(index, 10));+ if (!removed) {+ throw new ServerError('Drink entry not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(removed);+}));++// =============================================================================+// BLOOD & BODY+// =============================================================================++/**+ * GET /api/meatspace/blood+ * Blood test history + reference ranges+ */+router.get('/blood', asyncHandler(async (req, res) => {+ const data = await healthService.getBloodTests();+ res.json(data);+}));++/**+ * POST /api/meatspace/blood+ * Add a blood test+ */+router.post('/blood', asyncHandler(async (req, res) => {+ const data = validateRequest(bloodTestSchema, req.body);+ const test = await healthService.addBloodTest(data);+ res.status(201).json(test);+}));++/**+ * GET /api/meatspace/body+ * Body composition history+ */+router.get('/body', asyncHandler(async (req, res) => {+ const history = await healthService.getBodyHistory();+ res.json(history);+}));++/**+ * POST /api/meatspace/body+ * Log a body entry+ */+router.post('/body', asyncHandler(async (req, res) => {+ const data = validateRequest(bodyEntrySchema, req.body);+ const entry = await healthService.addBodyEntry(data);+ res.status(201).json(entry);+}));++/**+ * GET /api/meatspace/epigenetic+ * Elysium results+ */+router.get('/epigenetic', asyncHandler(async (req, res) => {+ const data = await healthService.getEpigeneticTests();+ res.json(data);+}));++/**+ * POST /api/meatspace/epigenetic+ * Add epigenetic test result+ */+router.post('/epigenetic', asyncHandler(async (req, res) => {+ const data = validateRequest(epigeneticTestSchema, req.body);+ const test = await healthService.addEpigeneticTest(data);+ res.status(201).json(test);+}));++/**+ * GET /api/meatspace/eyes+ * Eye Rx history+ */+router.get('/eyes', asyncHandler(async (req, res) => {+ const data = await healthService.getEyeExams();+ res.json(data);+}));++/**+ * POST /api/meatspace/eyes+ * Add eye exam+ */+router.post('/eyes', asyncHandler(async (req, res) => {+ const data = validateRequest(eyeExamSchema, req.body);+ const exam = await healthService.addEyeExam(data);+ res.status(201).json(exam);+}));++// =============================================================================+// NUTRITION+// =============================================================================++/**+ * GET /api/meatspace/nutrition+ * Nutrition summary + averages+ */+router.get('/nutrition', asyncHandler(async (req, res) => {+ const summary = await healthService.getNutritionSummary();+ res.json(summary);+}));++/**+ * GET /api/meatspace/nutrition/daily+ * Daily nutrition entries+ */+router.get('/nutrition/daily', asyncHandler(async (req, res) => {+ const entries = await healthService.getDailyNutrition(req.query.from, req.query.to);+ res.json(entries);+}));+// =============================================================================// IMPORT// =============================================================================diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.jsnew file mode 100644index 0000000000..ff6feab5a7--- /dev/null+++ b/server/services/meatspaceAlcohol.js@@ -0,0 +1,212 @@+/**+ * MeatSpace Alcohol Service+ *+ * Drink logging, standard drink calculation, and rolling averages.+ * Reads/writes daily-log.json entries for alcohol data.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');+const CONFIG_FILE = join(MEATSPACE_DIR, 'config.json');++// Cache for rolling averages (invalidated on writes)+let averageCache = null;+let averageCacheAt = 0;+const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes++// === Pure Functions ===++/**+ * Calculate standard drinks from oz and ABV.+ * 1 standard drink = 0.6 oz pure alcohol.+ */+export function computeStandardDrinks(oz, abv) {+ const pureAlcoholOz = oz * (abv / 100);+ return Math.round((pureAlcoholOz / 0.6) * 100) / 100;+}++/**+ * Compute rolling averages from daily entries.+ */+export function computeRollingAverages(entries, sex = 'male') {+ const now = new Date();+ const today = now.toISOString().split('T')[0];++ // Filter entries with alcohol data, sorted by date+ const alcoholEntries = entries+ .filter(e => e.alcohol?.standardDrinks > 0)+ .sort((a, b) => a.date.localeCompare(b.date));++ const allEntries = entries.sort((a, b) => a.date.localeCompare(b.date));++ // Today's total+ const todayEntry = allEntries.find(e => e.date === today);+ const todayDrinks = todayEntry?.alcohol?.standardDrinks || 0;++ // Helper: average over last N days (including zero-drink days)+ const rollingAverage = (days) => {+ const cutoff = new Date(now);+ cutoff.setDate(cutoff.getDate() - days);+ const cutoffStr = cutoff.toISOString().split('T')[0];++ let totalDrinks = 0;+ let dayCount = 0;++ for (const entry of allEntries) {+ if (entry.date >= cutoffStr && entry.date <= today) {+ totalDrinks += entry.alcohol?.standardDrinks || 0;+ dayCount++;+ }+ }++ // Use actual calendar days for denominator, not just entries+ return dayCount > 0 ? Math.round((totalDrinks / days) * 100) / 100 : 0;+ };++ // All-time average+ let allTimeAvg = 0;+ if (allEntries.length > 0) {+ const firstDate = new Date(allEntries[0].date);+ const totalDays = Math.max(1, Math.ceil((now - firstDate) / (24 * 60 * 60 * 1000)));+ const totalDrinks = allEntries.reduce((sum, e) => sum + (e.alcohol?.standardDrinks || 0), 0);+ allTimeAvg = Math.round((totalDrinks / totalDays) * 100) / 100;+ }++ // NIAAA thresholds+ const thresholds = sex === 'female'+ ? { dailyMax: 1, weeklyMax: 7 }+ : { dailyMax: 2, weeklyMax: 14 };++ const avg7day = rollingAverage(7);+ const weeklyTotal = Math.round(avg7day * 7 * 100) / 100;++ return {+ today: todayDrinks,+ avg7day,+ avg30day: rollingAverage(30),+ allTimeAvg,+ weeklyTotal,+ thresholds,+ riskLevel: weeklyTotal > thresholds.weeklyMax ? 'high'+ : weeklyTotal > thresholds.weeklyMax * 0.7 ? 'moderate'+ : 'low',+ drinkingDays: alcoholEntries.length,+ totalEntries: allEntries.length+ };+}++// === File I/O ===++async function loadDailyLog() {+ return readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null });+}++async function saveDailyLog(log) {+ await ensureDir(MEATSPACE_DIR);+ await writeFile(DAILY_LOG_FILE, JSON.stringify(log, null, 2));+ averageCache = null; // Invalidate cache+}++// === Exported Service Functions ===++export async function getAlcoholSummary() {+ const now = Date.now();+ if (averageCache && (now - averageCacheAt < CACHE_TTL_MS)) {+ return averageCache;+ }++ const [log, config] = await Promise.all([+ loadDailyLog(),+ readJSONFile(CONFIG_FILE, { sex: 'male' })+ ]);++ const averages = computeRollingAverages(log.entries || [], config.sex || 'male');++ // Recent drinks (last 7 days)+ const today = new Date().toISOString().split('T')[0];+ const weekAgo = new Date();+ weekAgo.setDate(weekAgo.getDate() - 7);+ const weekAgoStr = weekAgo.toISOString().split('T')[0];++ const recentEntries = (log.entries || [])+ .filter(e => e.date >= weekAgoStr && e.date <= today && e.alcohol?.drinks?.length > 0)+ .sort((a, b) => b.date.localeCompare(a.date)); // Newest first++ averageCache = { ...averages, recentEntries };+ averageCacheAt = now;++ return averageCache;+}++export async function getDailyAlcohol(from, to) {+ const log = await loadDailyLog();+ let entries = (log.entries || []).filter(e => e.alcohol?.drinks?.length > 0);++ if (from) entries = entries.filter(e => e.date >= from);+ if (to) entries = entries.filter(e => e.date <= to);++ return entries.sort((a, b) => b.date.localeCompare(a.date));+}++export async function logDrink({ name, oz, abv, count = 1, date }) {+ const log = await loadDailyLog();+ const targetDate = date || new Date().toISOString().split('T')[0];++ const standardDrinks = computeStandardDrinks(oz * count, abv);+ const drink = { name: name || '', abv, oz, count };++ // Find or create daily entry+ let entry = log.entries.find(e => e.date === targetDate);+ if (!entry) {+ entry = { date: targetDate };+ log.entries.push(entry);+ }++ // Initialize alcohol section+ if (!entry.alcohol) {+ entry.alcohol = { drinks: [], standardDrinks: 0 };+ }++ entry.alcohol.drinks.push(drink);++ // Recalculate total standard drinks for the day+ entry.alcohol.standardDrinks = entry.alcohol.drinks.reduce((sum, d) => {+ return sum + computeStandardDrinks((d.oz || 0) * (d.count || 1), d.abv || 0);+ }, 0);+ entry.alcohol.standardDrinks = Math.round(entry.alcohol.standardDrinks * 100) / 100;++ // Re-sort and update lastEntryDate+ log.entries.sort((a, b) => a.date.localeCompare(b.date));+ log.lastEntryDate = log.entries[log.entries.length - 1].date;++ await saveDailyLog(log);+ console.log(`🍺 Logged drink: ${name || 'unnamed'} ${oz}oz @ ${abv}% (${standardDrinks} std drinks) on ${targetDate}`);++ return { drink, standardDrinks, date: targetDate, dayTotal: entry.alcohol.standardDrinks };+}++export async function removeDrink(date, index) {+ const log = await loadDailyLog();+ const entry = log.entries.find(e => e.date === date);+ if (!entry?.alcohol?.drinks?.[index]) return null;++ const removed = entry.alcohol.drinks.splice(index, 1)[0];++ // Recalculate total+ entry.alcohol.standardDrinks = entry.alcohol.drinks.reduce((sum, d) => {+ return sum + computeStandardDrinks((d.oz || 0) * (d.count || 1), d.abv || 0);+ }, 0);+ entry.alcohol.standardDrinks = Math.round(entry.alcohol.standardDrinks * 100) / 100;++ // Remove alcohol section if empty+ if (entry.alcohol.drinks.length === 0) {+ delete entry.alcohol;+ }++ await saveDailyLog(log);+ return removed;+}diff --git a/server/services/meatspaceAlcohol.test.js b/server/services/meatspaceAlcohol.test.jsnew file mode 100644index 0000000000..c5ee907b5f--- /dev/null+++ b/server/services/meatspaceAlcohol.test.js@@ -0,0 +1,202 @@+import { describe, it, expect } from 'vitest';++// Inline pure functions to avoid mocking file I/O++function computeStandardDrinks(oz, abv) {+ const pureAlcoholOz = oz * (abv / 100);+ return Math.round((pureAlcoholOz / 0.6) * 100) / 100;+}++function computeRollingAverages(entries, sex = 'male') {+ const now = new Date();+ const today = now.toISOString().split('T')[0];++ const alcoholEntries = entries+ .filter(e => e.alcohol?.standardDrinks > 0)+ .sort((a, b) => a.date.localeCompare(b.date));++ const allEntries = entries.sort((a, b) => a.date.localeCompare(b.date));++ const todayEntry = allEntries.find(e => e.date === today);+ const todayDrinks = todayEntry?.alcohol?.standardDrinks || 0;++ const rollingAverage = (days) => {+ const cutoff = new Date(now);+ cutoff.setDate(cutoff.getDate() - days);+ const cutoffStr = cutoff.toISOString().split('T')[0];++ let totalDrinks = 0;+ let dayCount = 0;++ for (const entry of allEntries) {+ if (entry.date >= cutoffStr && entry.date <= today) {+ totalDrinks += entry.alcohol?.standardDrinks || 0;+ dayCount++;+ }+ }++ return dayCount > 0 ? Math.round((totalDrinks / days) * 100) / 100 : 0;+ };++ let allTimeAvg = 0;+ if (allEntries.length > 0) {+ const firstDate = new Date(allEntries[0].date);+ const totalDays = Math.max(1, Math.ceil((now - firstDate) / (24 * 60 * 60 * 1000)));+ const totalDrinks = allEntries.reduce((sum, e) => sum + (e.alcohol?.standardDrinks || 0), 0);+ allTimeAvg = Math.round((totalDrinks / totalDays) * 100) / 100;+ }++ const thresholds = sex === 'female'+ ? { dailyMax: 1, weeklyMax: 7 }+ : { dailyMax: 2, weeklyMax: 14 };++ const avg7day = rollingAverage(7);+ const weeklyTotal = Math.round(avg7day * 7 * 100) / 100;++ return {+ today: todayDrinks,+ avg7day,+ avg30day: rollingAverage(30),+ allTimeAvg,+ weeklyTotal,+ thresholds,+ riskLevel: weeklyTotal > thresholds.weeklyMax ? 'high'+ : weeklyTotal > thresholds.weeklyMax * 0.7 ? 'moderate'+ : 'low',+ drinkingDays: alcoholEntries.length,+ totalEntries: allEntries.length+ };+}++// =============================================================================+// STANDARD DRINKS TESTS+// =============================================================================++describe('computeStandardDrinks', () => {+ it('calculates standard drinks for a 12oz 5% beer', () => {+ expect(computeStandardDrinks(12, 5)).toBe(1);+ });++ it('calculates standard drinks for a 5oz 12% wine', () => {+ expect(computeStandardDrinks(5, 12)).toBe(1);+ });++ it('calculates standard drinks for a 1.5oz 40% spirit', () => {+ expect(computeStandardDrinks(1.5, 40)).toBe(1);+ });++ it('handles Guinness (14.9oz @ 4.2%)', () => {+ // 14.9 * 0.042 = 0.6258 oz pure alcohol / 0.6 = 1.043+ expect(computeStandardDrinks(14.9, 4.2)).toBe(1.04);+ });++ it('handles double IPA pint (16oz @ 8%)', () => {+ // 16 * 0.08 = 1.28 / 0.6 = 2.1333+ expect(computeStandardDrinks(16, 8)).toBe(2.13);+ });++ it('returns 0 for 0 ABV', () => {+ expect(computeStandardDrinks(12, 0)).toBe(0);+ });++ it('returns 0 for 0 oz', () => {+ expect(computeStandardDrinks(0, 5)).toBe(0);+ });+});++// =============================================================================+// ROLLING AVERAGES TESTS+// =============================================================================++describe('computeRollingAverages', () => {+ // Helper to make dates relative to today+ const daysAgo = (n) => {+ const d = new Date();+ d.setDate(d.getDate() - n);+ return d.toISOString().split('T')[0];+ };++ it('returns zeros for empty entries', () => {+ const result = computeRollingAverages([]);+ expect(result.today).toBe(0);+ expect(result.avg7day).toBe(0);+ expect(result.avg30day).toBe(0);+ expect(result.allTimeAvg).toBe(0);+ expect(result.riskLevel).toBe('low');+ });++ it('computes today drinks from matching entry', () => {+ const today = new Date().toISOString().split('T')[0];+ const entries = [+ { date: today, alcohol: { standardDrinks: 2.5, drinks: [{ name: 'Beer', oz: 12, abv: 5 }] } }+ ];+ const result = computeRollingAverages(entries);+ expect(result.today).toBe(2.5);+ });++ it('computes 7-day rolling average', () => {+ const entries = [];+ for (let i = 0; i < 7; i++) {+ entries.push({+ date: daysAgo(i),+ alcohol: { standardDrinks: 2, drinks: [{}] }+ });+ }+ const result = computeRollingAverages(entries);+ expect(result.avg7day).toBe(2); // 14 drinks / 7 days+ expect(result.weeklyTotal).toBe(14);+ });++ it('uses female NIAAA thresholds', () => {+ const entries = [];+ for (let i = 0; i < 7; i++) {+ entries.push({+ date: daysAgo(i),+ alcohol: { standardDrinks: 1.5, drinks: [{}] }+ });+ }+ const result = computeRollingAverages(entries, 'female');+ expect(result.thresholds.weeklyMax).toBe(7);+ expect(result.weeklyTotal).toBe(10.5);+ expect(result.riskLevel).toBe('high');+ });++ it('classifies moderate risk correctly', () => {+ // Male weekly max = 14, 70% = 9.8+ // 11 drinks/week should be moderate+ const entries = [];+ for (let i = 0; i < 7; i++) {+ entries.push({+ date: daysAgo(i),+ alcohol: { standardDrinks: 11 / 7, drinks: [{}] }+ });+ }+ const result = computeRollingAverages(entries, 'male');+ expect(result.riskLevel).toBe('moderate');+ });++ it('classifies low risk correctly', () => {+ const entries = [+ { date: daysAgo(0), alcohol: { standardDrinks: 1, drinks: [{}] } },+ { date: daysAgo(1) },+ { date: daysAgo(2) },+ { date: daysAgo(3) },+ { date: daysAgo(4) },+ { date: daysAgo(5) },+ { date: daysAgo(6) }+ ];+ const result = computeRollingAverages(entries, 'male');+ expect(result.riskLevel).toBe('low');+ });++ it('counts drinking days separately from total entries', () => {+ const entries = [+ { date: daysAgo(0), alcohol: { standardDrinks: 2, drinks: [{}] } },+ { date: daysAgo(1) }, // no alcohol+ { date: daysAgo(2), alcohol: { standardDrinks: 1, drinks: [{}] } }+ ];+ const result = computeRollingAverages(entries);+ expect(result.drinkingDays).toBe(2);+ expect(result.totalEntries).toBe(3);+ });+});diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.jsnew file mode 100644index 0000000000..14a35479c1--- /dev/null+++ b/server/services/meatspaceHealth.js@@ -0,0 +1,165 @@+/**+ * MeatSpace Health Service+ *+ * Blood tests, body composition, epigenetic tests, eyes, and nutrition CRUD.+ * Reads/writes to meatspace data files.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');+const BLOOD_TESTS_FILE = join(MEATSPACE_DIR, 'blood-tests.json');+const EPIGENETIC_TESTS_FILE = join(MEATSPACE_DIR, 'epigenetic-tests.json');+const EYES_FILE = join(MEATSPACE_DIR, 'eyes.json');++async function ensureMeatspaceDir() {+ await ensureDir(MEATSPACE_DIR);+}++// === Blood Tests ===++export async function getBloodTests() {+ return readJSONFile(BLOOD_TESTS_FILE, { tests: [], referenceRanges: {} });+}++export async function addBloodTest(test) {+ const data = await getBloodTests();+ data.tests.push(test);+ data.tests.sort((a, b) => a.date.localeCompare(b.date));+ await ensureMeatspaceDir();+ await writeFile(BLOOD_TESTS_FILE, JSON.stringify(data, null, 2));+ console.log(`🩸 Blood test added for ${test.date}`);+ return test;+}++// === Body Composition ===++export async function getBodyHistory() {+ const log = await readJSONFile(DAILY_LOG_FILE, { entries: [] });+ return (log.entries || [])+ .filter(e => e.body && Object.keys(e.body).length > 0)+ .map(e => ({ date: e.date, ...e.body }))+ .sort((a, b) => a.date.localeCompare(b.date));+}++export async function addBodyEntry({ date, ...body }) {+ const log = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null });+ const targetDate = date || new Date().toISOString().split('T')[0];++ let entry = log.entries.find(e => e.date === targetDate);+ if (!entry) {+ entry = { date: targetDate };+ log.entries.push(entry);+ }++ entry.body = { ...(entry.body || {}), ...body };++ log.entries.sort((a, b) => a.date.localeCompare(b.date));+ log.lastEntryDate = log.entries[log.entries.length - 1].date;++ await ensureMeatspaceDir();+ await writeFile(DAILY_LOG_FILE, JSON.stringify(log, null, 2));+ console.log(`⚖️ Body entry added for ${targetDate}`);+ return { date: targetDate, ...entry.body };+}++// === Epigenetic Tests ===++export async function getEpigeneticTests() {+ return readJSONFile(EPIGENETIC_TESTS_FILE, { tests: [] });+}++export async function addEpigeneticTest(test) {+ const data = await getEpigeneticTests();+ data.tests.push(test);+ data.tests.sort((a, b) => a.date.localeCompare(b.date));+ await ensureMeatspaceDir();+ await writeFile(EPIGENETIC_TESTS_FILE, JSON.stringify(data, null, 2));+ console.log(`🧬 Epigenetic test added for ${test.date}`);+ return test;+}++// === Eyes ===++export async function getEyeExams() {+ return readJSONFile(EYES_FILE, { exams: [] });+}++export async function addEyeExam(exam) {+ const data = await getEyeExams();+ data.exams.push(exam);+ data.exams.sort((a, b) => a.date.localeCompare(b.date));+ await ensureMeatspaceDir();+ await writeFile(EYES_FILE, JSON.stringify(data, null, 2));+ console.log(`👁️ Eye exam added for ${exam.date}`);+ return exam;+}++// === Nutrition ===++export async function getNutritionSummary() {+ const log = await readJSONFile(DAILY_LOG_FILE, { entries: [] });+ const entries = (log.entries || []).filter(e => e.nutrition && Object.keys(e.nutrition).length > 0);++ if (entries.length === 0) {+ return { entries: [], averages: null, totalEntries: 0 };+ }++ // Compute averages+ const sums = {};+ const counts = {};+ for (const entry of entries) {+ for (const [key, val] of Object.entries(entry.nutrition)) {+ if (val != null) {+ sums[key] = (sums[key] || 0) + val;+ counts[key] = (counts[key] || 0) + 1;+ }+ }+ }++ const averages = {};+ for (const key of Object.keys(sums)) {+ averages[key] = Math.round((sums[key] / counts[key]) * 10) / 10;+ }++ // Last 7 days of nutrition+ const today = new Date().toISOString().split('T')[0];+ const weekAgo = new Date();+ weekAgo.setDate(weekAgo.getDate() - 7);+ const weekAgoStr = weekAgo.toISOString().split('T')[0];++ const recentEntries = entries+ .filter(e => e.date >= weekAgoStr && e.date <= today)+ .sort((a, b) => b.date.localeCompare(a.date));++ // Mercury exposure+ const mercuryEntries = (log.entries || []).filter(e => e.mercuryMg);+ const totalMercury = mercuryEntries.reduce((sum, e) => sum + e.mercuryMg, 0);+ const avgMercury = mercuryEntries.length > 0+ ? Math.round((totalMercury / mercuryEntries.length) * 1000) / 1000+ : null;++ return {+ totalEntries: entries.length,+ averages,+ recentEntries,+ mercury: {+ avgDailyMg: avgMercury,+ daysTracked: mercuryEntries.length+ }+ };+}++export async function getDailyNutrition(from, to) {+ const log = await readJSONFile(DAILY_LOG_FILE, { entries: [] });+ let entries = (log.entries || []).filter(e => e.nutrition && Object.keys(e.nutrition).length > 0);++ if (from) entries = entries.filter(e => e.date >= from);+ if (to) entries = entries.filter(e => e.date <= to);++ return entries.map(e => ({ date: e.date, ...e.nutrition, mercuryMg: e.mercuryMg }))+ .sort((a, b) => b.date.localeCompare(a.date));+}diff --git a/server/services/meatspaceHealth.test.js b/server/services/meatspaceHealth.test.jsnew file mode 100644index 0000000000..1d2dae56ec--- /dev/null+++ b/server/services/meatspaceHealth.test.js@@ -0,0 +1,225 @@+import { describe, it, expect } from 'vitest';++// Inline pure functions to avoid mocking file I/O++function computeNutritionAverages(entries) {+ if (entries.length === 0) return null;++ const sums = {};+ const counts = {};+ for (const entry of entries) {+ for (const [key, val] of Object.entries(entry.nutrition)) {+ if (val != null) {+ sums[key] = (sums[key] || 0) + val;+ counts[key] = (counts[key] || 0) + 1;+ }+ }+ }++ const averages = {};+ for (const key of Object.keys(sums)) {+ averages[key] = Math.round((sums[key] / counts[key]) * 10) / 10;+ }+ return averages;+}++function computeMercuryStats(entries) {+ const mercuryEntries = entries.filter(e => e.mercuryMg);+ if (mercuryEntries.length === 0) return { avgDailyMg: null, daysTracked: 0 };++ const total = mercuryEntries.reduce((sum, e) => sum + e.mercuryMg, 0);+ return {+ avgDailyMg: Math.round((total / mercuryEntries.length) * 1000) / 1000,+ daysTracked: mercuryEntries.length+ };+}++function extractBodyHistory(entries) {+ return entries+ .filter(e => e.body && Object.keys(e.body).length > 0)+ .map(e => ({ date: e.date, ...e.body }))+ .sort((a, b) => a.date.localeCompare(b.date));+}++function mergeBodyEntry(existingBody, newBody) {+ return { ...(existingBody || {}), ...newBody };+}++function sortByDate(items) {+ return [...items].sort((a, b) => a.date.localeCompare(b.date));+}++// =============================================================================+// NUTRITION AVERAGES TESTS+// =============================================================================++describe('computeNutritionAverages', () => {+ it('returns null for empty entries', () => {+ expect(computeNutritionAverages([])).toBeNull();+ });++ it('computes averages for single entry', () => {+ const entries = [{ nutrition: { calories: 2000, fatG: 80, carbG: 250 } }];+ const result = computeNutritionAverages(entries);+ expect(result.calories).toBe(2000);+ expect(result.fatG).toBe(80);+ expect(result.carbG).toBe(250);+ });++ it('computes averages across multiple entries', () => {+ const entries = [+ { nutrition: { calories: 1500, fatG: 60 } },+ { nutrition: { calories: 2500, fatG: 100 } }+ ];+ const result = computeNutritionAverages(entries);+ expect(result.calories).toBe(2000);+ expect(result.fatG).toBe(80);+ });++ it('handles sparse data (some fields missing)', () => {+ const entries = [+ { nutrition: { calories: 1800, fiberG: 30 } },+ { nutrition: { calories: 2200 } }+ ];+ const result = computeNutritionAverages(entries);+ expect(result.calories).toBe(2000);+ expect(result.fiberG).toBe(30); // only 1 entry had fiber+ });++ it('skips null values in averages', () => {+ const entries = [+ { nutrition: { calories: 2000, fatG: null } },+ { nutrition: { calories: 1800, fatG: 70 } }+ ];+ const result = computeNutritionAverages(entries);+ expect(result.calories).toBe(1900);+ expect(result.fatG).toBe(70); // only counted non-null+ });++ it('rounds to one decimal place', () => {+ const entries = [+ { nutrition: { calories: 1000 } },+ { nutrition: { calories: 1001 } },+ { nutrition: { calories: 1002 } }+ ];+ const result = computeNutritionAverages(entries);+ expect(result.calories).toBe(1001);+ });+});++// =============================================================================+// MERCURY STATS TESTS+// =============================================================================++describe('computeMercuryStats', () => {+ it('returns null avg for no mercury entries', () => {+ const result = computeMercuryStats([{ date: '2024-01-01' }]);+ expect(result.avgDailyMg).toBeNull();+ expect(result.daysTracked).toBe(0);+ });++ it('computes average mercury exposure', () => {+ const entries = [+ { date: '2024-01-01', mercuryMg: 0.010 },+ { date: '2024-01-02', mercuryMg: 0.030 },+ { date: '2024-01-03', mercuryMg: 0.020 }+ ];+ const result = computeMercuryStats(entries);+ expect(result.avgDailyMg).toBe(0.02);+ expect(result.daysTracked).toBe(3);+ });++ it('skips entries without mercury data', () => {+ const entries = [+ { date: '2024-01-01', mercuryMg: 0.040 },+ { date: '2024-01-02' },+ { date: '2024-01-03', mercuryMg: 0.020 }+ ];+ const result = computeMercuryStats(entries);+ expect(result.avgDailyMg).toBe(0.03);+ expect(result.daysTracked).toBe(2);+ });+});++// =============================================================================+// BODY HISTORY TESTS+// =============================================================================++describe('extractBodyHistory', () => {+ it('returns empty array for no body entries', () => {+ const entries = [+ { date: '2024-01-01', nutrition: { calories: 2000 } }+ ];+ expect(extractBodyHistory(entries)).toEqual([]);+ });++ it('extracts and sorts body entries', () => {+ const entries = [+ { date: '2024-03-01', body: { weightLbs: 160 } },+ { date: '2024-01-01', body: { weightLbs: 165 } },+ { date: '2024-02-01', body: { weightLbs: 162 } }+ ];+ const result = extractBodyHistory(entries);+ expect(result).toHaveLength(3);+ expect(result[0].date).toBe('2024-01-01');+ expect(result[0].weightLbs).toBe(165);+ expect(result[2].date).toBe('2024-03-01');+ });++ it('filters out entries with empty body objects', () => {+ const entries = [+ { date: '2024-01-01', body: {} },+ { date: '2024-01-02', body: { weightLbs: 160 } }+ ];+ const result = extractBodyHistory(entries);+ expect(result).toHaveLength(1);+ expect(result[0].date).toBe('2024-01-02');+ });+});++// =============================================================================+// BODY ENTRY MERGE TESTS+// =============================================================================++describe('mergeBodyEntry', () => {+ it('creates body from scratch when no existing data', () => {+ const result = mergeBodyEntry(null, { weightLbs: 160 });+ expect(result).toEqual({ weightLbs: 160 });+ });++ it('merges new fields into existing body', () => {+ const existing = { weightLbs: 160 };+ const result = mergeBodyEntry(existing, { fatPct: 15 });+ expect(result).toEqual({ weightLbs: 160, fatPct: 15 });+ });++ it('overwrites existing fields', () => {+ const existing = { weightLbs: 160, fatPct: 15 };+ const result = mergeBodyEntry(existing, { weightLbs: 158 });+ expect(result).toEqual({ weightLbs: 158, fatPct: 15 });+ });+});++// =============================================================================+// SORT TESTS+// =============================================================================++describe('sortByDate', () => {+ it('sorts chronologically', () => {+ const items = [+ { date: '2024-12-01' },+ { date: '2024-01-15' },+ { date: '2024-06-20' }+ ];+ const result = sortByDate(items);+ expect(result[0].date).toBe('2024-01-15');+ expect(result[1].date).toBe('2024-06-20');+ expect(result[2].date).toBe('2024-12-01');+ });++ it('does not mutate original array', () => {+ const items = [{ date: '2024-12-01' }, { date: '2024-01-01' }];+ sortByDate(items);+ expect(items[0].date).toBe('2024-12-01');+ });+});