Skip to content

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

feat(03-03): create correlation charts and wire Health tab into MeatSpace

Adam Eivy81bd182cb637
diff --git a/.changelog/v1.9.x.md b/.changelog/v1.9.x.md
index 9e50a12b1b..074fdc9ab3 100644
--- a/.changelog/v1.9.x.md
+++ b/.changelog/v1.9.x.md
@@ -37,3 +37,15 @@ MeatSpace Phases 2-5: Complete health tracking with alcohol logging, blood/body/
### MeatSpace Phase 5 — Polish
- **Dashboard death clock widget**: Compact live countdown on main Dashboard with link to MeatSpace overview, shows life expectancy and percent complete
+
+### Apple Health Integration (Phase 03)
+- **Health tab in MeatSpace**: New dedicated Health tab at `/meatspace/health` with four metric cards: Steps, Heart Rate, Sleep, and HRV
+- **Time range selector**: 7d/30d/90d/1y buttons filter all health cards consistently via parallel API fetches
+- **Steps card**: Daily average hero number + LineChart trend from Apple Health step_count data
+- **Heart Rate card**: Average BPM hero + LineChart trend from Apple Health heart_rate data
+- **Sleep card**: Average hours hero + stacked horizontal BarChart showing deep/REM/core/awake stage proportions (last 7 days)
+- **HRV card**: Average ms hero + LineChart trend from Apple Health heart_rate_variability_sdnn data
+- **Alcohol vs HRV correlation**: Dual-axis ComposedChart (Line + Bar) with auto-generated computed text summary comparing HRV on drinking vs sober days
+- **Activity vs Blood Work correlation**: 30-day rolling average steps paired with blood marker Lines at blood test dates, with per-test text summary
+- **Minimum data threshold**: Both correlation charts show "Need 14+ days" message when insufficient data exists
+- Apple Health data ingestion via POST `/api/health/ingest`, daily aggregates at `/api/health/metrics/:name/daily`, correlation at `/api/health/correlation`
diff --git a/client/src/components/meatspace/ActivityBloodCorrelation.jsx b/client/src/components/meatspace/ActivityBloodCorrelation.jsx
new file mode 100644
index 0000000000..3018a43227
--- /dev/null
+++ b/client/src/components/meatspace/ActivityBloodCorrelation.jsx
@@ -0,0 +1,156 @@
+import {
+ ComposedChart, Bar, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer
+} from 'recharts';
+
+// Blood markers to chart — prefer common ones if available in the test results
+const PREFERRED_MARKERS = ['cholesterol', 'glucose', 'ldl', 'hdl', 'triglycerides'];
+
+function compute30DayRollingAvg(dailyData, testDate) {
+ const cutoff = new Date(testDate);
+ const windowStart = new Date(testDate);
+ windowStart.setDate(windowStart.getDate() - 30);
+ const startStr = windowStart.toISOString().split('T')[0];
+
+ const window = dailyData.filter(d => d.date >= startStr && d.date < testDate && d.steps != null);
+ if (window.length === 0) return null;
+ return Math.round(window.reduce((sum, d) => sum + d.steps, 0) / window.length);
+}
+
+function pickMarkers(bloodTests) {
+ // Find which preferred markers appear in any test
+ const found = [];
+ for (const marker of PREFERRED_MARKERS) {
+ if (bloodTests.some(t => t.results?.[marker] != null || t[marker] != null)) {
+ found.push(marker);
+ if (found.length === 3) break;
+ }
+ }
+ return found;
+}
+
+const MARKER_COLORS = ['#3b82f6', '#8b5cf6', '#f59e0b'];
+
+const CustomTooltip = ({ active, payload, label }) => {
+ if (!active || !payload?.length) return null;
+ return (
+ <div style={{ background: '#1a1a1a', border: '1px solid #2a2a2a', color: '#fff', padding: '8px', borderRadius: '6px', fontSize: '12px' }}>
+ <p style={{ color: '#9ca3af', marginBottom: 4 }}>{label}</p>
+ {payload.map((entry) => (
+ <p key={entry.dataKey} style={{ color: entry.color ?? entry.fill, margin: '2px 0' }}>
+ {entry.name}: {entry.value != null ? Math.round(entry.value).toLocaleString() : '—'}
+ {entry.dataKey === 'steps' ? ' steps/day' : ''}
+ </p>
+ ))}
+ </div>
+ );
+};
+
+export default function ActivityBloodCorrelation({ data, range }) {
+ const dailyData = data?.dailyData ?? [];
+ const bloodTests = data?.bloodTests ?? [];
+
+ if (dailyData.length < 14) {
+ 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-3">Activity vs Blood Work</h3>
+ <p className="text-gray-400 text-sm">
+ Need 14+ days of data for correlations — {dailyData.length} days so far.
+ </p>
+ </div>
+ );
+ }
+
+ if (bloodTests.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-3">Activity vs Blood Work</h3>
+ <p className="text-gray-400 text-sm">No blood tests in this period to correlate with activity.</p>
+ </div>
+ );
+ }
+
+ const markers = pickMarkers(bloodTests);
+
+ // Build chart data: one entry per blood test
+ const chartData = bloodTests.map(test => {
+ const stepsAvg = compute30DayRollingAvg(dailyData, test.date);
+ const entry = {
+ date: test.date?.slice(5) ?? test.date,
+ fullDate: test.date,
+ steps: stepsAvg
+ };
+ for (const marker of markers) {
+ entry[marker] = test.results?.[marker] ?? test[marker] ?? null;
+ }
+ return entry;
+ });
+
+ // Build a summary sentence for each test
+ const summaries = bloodTests.map(test => {
+ const avg = compute30DayRollingAvg(dailyData, test.date);
+ if (avg == null) return null;
+ return `Average ${avg.toLocaleString()} steps/day in the 30 days before your ${test.date} blood test`;
+ }).filter(Boolean);
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-6">
+ <div className="flex items-center gap-2 mb-4">
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Activity vs Blood Work</h3>
+ <span className="text-xs text-gray-600 ml-1">({range})</span>
+ </div>
+
+ <ResponsiveContainer width="100%" height={220}>
+ <ComposedChart data={chartData} margin={{ top: 5, right: 40, bottom: 5, left: 0 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />
+ <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} />
+ <YAxis
+ yAxisId="steps"
+ orientation="left"
+ tick={{ fill: '#9ca3af', fontSize: 11 }}
+ width={60}
+ tickFormatter={v => v.toLocaleString()}
+ label={{ value: 'Steps (30d avg)', angle: -90, position: 'insideLeft', fill: '#9ca3af', fontSize: 10 }}
+ />
+ {markers.length > 0 && (
+ <YAxis
+ yAxisId="markers"
+ orientation="right"
+ tick={{ fill: '#9ca3af', fontSize: 11 }}
+ width={40}
+ label={{ value: 'Blood (mg/dL)', angle: 90, position: 'insideRight', fill: '#9ca3af', fontSize: 10 }}
+ />
+ )}
+ <Tooltip content={<CustomTooltip />} />
+ <Legend wrapperStyle={{ fontSize: 11, color: '#9ca3af' }} />
+ <Bar
+ yAxisId="steps"
+ dataKey="steps"
+ name="30d Avg Steps"
+ fill="#6b7280"
+ opacity={0.6}
+ maxBarSize={40}
+ />
+ {markers.map((marker, i) => (
+ <Line
+ key={marker}
+ yAxisId="markers"
+ type="monotone"
+ dataKey={marker}
+ name={marker.charAt(0).toUpperCase() + marker.slice(1)}
+ stroke={MARKER_COLORS[i]}
+ strokeWidth={2}
+ dot={{ r: 4, fill: MARKER_COLORS[i] }}
+ connectNulls
+ />
+ ))}
+ </ComposedChart>
+ </ResponsiveContainer>
+
+ {summaries.length > 0 && (
+ <div className="text-sm text-gray-400 mt-3 border-t border-port-border pt-3 space-y-1">
+ {summaries.map((s, i) => <p key={i}>{s}</p>)}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/AlcoholHrvCorrelation.jsx b/client/src/components/meatspace/AlcoholHrvCorrelation.jsx
new file mode 100644
index 0000000000..e3dafe612c
--- /dev/null
+++ b/client/src/components/meatspace/AlcoholHrvCorrelation.jsx
@@ -0,0 +1,116 @@
+import { HeartPulse, Beer } from 'lucide-react';
+import {
+ ComposedChart, Line, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer
+} from 'recharts';
+
+const CustomTooltip = ({ active, payload, label }) => {
+ if (!active || !payload?.length) return null;
+ return (
+ <div style={{ background: '#1a1a1a', border: '1px solid #2a2a2a', color: '#fff', padding: '8px', borderRadius: '6px', fontSize: '12px' }}>
+ <p style={{ color: '#9ca3af', marginBottom: 4 }}>{label}</p>
+ {payload.map((entry) => (
+ <p key={entry.dataKey} style={{ color: entry.color ?? entry.fill, margin: '2px 0' }}>
+ {entry.name}: {entry.value != null ? Math.round(entry.value * 100) / 100 : '—'}
+ {entry.dataKey === 'hrv' ? ' ms' : 'g'}
+ </p>
+ ))}
+ </div>
+ );
+};
+
+function computeSummary(dailyData) {
+ const drinkingDays = dailyData.filter(d => d.alcoholGrams != null && d.alcoholGrams > 0 && d.hrv != null);
+ const soberDays = dailyData.filter(d => (d.alcoholGrams == null || d.alcoholGrams === 0) && d.hrv != null);
+
+ if (drinkingDays.length === 0) return 'No alcohol data recorded in this period.';
+ if (soberDays.length === 0) return 'No sober days recorded in this period.';
+
+ const avgHrvDrinking = Math.round(drinkingDays.reduce((sum, d) => sum + d.hrv, 0) / drinkingDays.length);
+ const avgHrvSober = Math.round(soberDays.reduce((sum, d) => sum + d.hrv, 0) / soberDays.length);
+ const percentDiff = avgHrvSober > 0
+ ? Math.abs(((avgHrvSober - avgHrvDrinking) / avgHrvSober) * 100).toFixed(0)
+ : '0';
+
+ return `HRV averages ${avgHrvDrinking}ms on drinking days vs ${avgHrvSober}ms on sober days (${percentDiff}% difference)`;
+}
+
+export default function AlcoholHrvCorrelation({ data, range }) {
+ const dailyData = data?.dailyData ?? [];
+
+ if (dailyData.length < 14) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-6">
+ <div className="flex items-center gap-2 mb-3">
+ <HeartPulse size={16} className="text-port-success" />
+ <Beer size={16} className="text-port-warning" />
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Alcohol vs HRV</h3>
+ </div>
+ <p className="text-gray-400 text-sm">
+ Need 14+ days of data for correlations — {dailyData.length} days so far.
+ </p>
+ </div>
+ );
+ }
+
+ const chartData = dailyData.map(d => ({
+ date: d.date?.slice(5) ?? d.date,
+ hrv: d.hrv,
+ alcohol: d.alcoholGrams
+ }));
+
+ const summary = computeSummary(dailyData);
+
+ 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={16} className="text-port-success" />
+ <Beer size={16} className="text-port-warning" />
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Alcohol vs HRV</h3>
+ <span className="text-xs text-gray-600 ml-1">({range})</span>
+ </div>
+
+ <ResponsiveContainer width="100%" height={220}>
+ <ComposedChart data={chartData} margin={{ top: 5, right: 40, bottom: 5, left: 0 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />
+ <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} interval="preserveStartEnd" />
+ <YAxis
+ yAxisId="hrv"
+ orientation="left"
+ tick={{ fill: '#9ca3af', fontSize: 11 }}
+ width={40}
+ label={{ value: 'HRV (ms)', angle: -90, position: 'insideLeft', fill: '#9ca3af', fontSize: 10 }}
+ />
+ <YAxis
+ yAxisId="alcohol"
+ orientation="right"
+ tick={{ fill: '#9ca3af', fontSize: 11 }}
+ width={40}
+ label={{ value: 'Alcohol (g)', angle: 90, position: 'insideRight', fill: '#9ca3af', fontSize: 10 }}
+ />
+ <Tooltip content={<CustomTooltip />} />
+ <Legend wrapperStyle={{ fontSize: 11, color: '#9ca3af' }} />
+ <Line
+ yAxisId="hrv"
+ type="monotone"
+ dataKey="hrv"
+ name="HRV"
+ stroke="#22c55e"
+ strokeWidth={2}
+ dot={false}
+ connectNulls
+ />
+ <Bar
+ yAxisId="alcohol"
+ dataKey="alcohol"
+ name="Alcohol"
+ fill="#f59e0b"
+ opacity={0.7}
+ maxBarSize={12}
+ />
+ </ComposedChart>
+ </ResponsiveContainer>
+
+ <p className="text-sm text-gray-400 mt-3 border-t border-port-border pt-3">{summary}</p>
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/constants.js b/client/src/components/meatspace/constants.js
index 9f4a36a56a..52c74c69bc 100644
--- a/client/src/components/meatspace/constants.js
+++ b/client/src/components/meatspace/constants.js
@@ -4,7 +4,8 @@ import {
Dna,
HeartPulse,
ClipboardList,
- Activity
+ Activity,
+ Stethoscope
} from 'lucide-react';
export const TABS = [
@@ -12,6 +13,7 @@ export const TABS = [
{ id: 'alcohol', label: 'Alcohol', icon: Beer },
{ id: 'blood', label: 'Blood & Body', icon: HeartPulse },
{ id: 'genome', label: 'Genome', icon: Dna },
+ { id: 'health', label: 'Health', icon: Stethoscope },
{ id: 'lifestyle', label: 'Lifestyle', icon: ClipboardList }
];
diff --git a/client/src/components/meatspace/tabs/HealthTab.jsx b/client/src/components/meatspace/tabs/HealthTab.jsx
index ddd1243425..7dafe0decc 100644
--- a/client/src/components/meatspace/tabs/HealthTab.jsx
+++ b/client/src/components/meatspace/tabs/HealthTab.jsx
@@ -4,6 +4,8 @@ import StepsCard from '../StepsCard';
import HeartRateCard from '../HeartRateCard';
import SleepCard from '../SleepCard';
import HrvCard from '../HrvCard';
+import AlcoholHrvCorrelation from '../AlcoholHrvCorrelation';
+import ActivityBloodCorrelation from '../ActivityBloodCorrelation';
const RANGES = [
{ id: '7d', label: '7d', days: 7 },
@@ -80,8 +82,13 @@ export default function HealthTab() {
<HrvCard data={hrvData} loading={loading} />
</div>
- {/* Correlation charts — wired in Task 2 */}
- <div />
+ {/* Correlation charts */}
+ {correlationData && (
+ <>
+ <AlcoholHrvCorrelation data={correlationData} range={range} />
+ <ActivityBloodCorrelation data={correlationData} range={range} />
+ </>
+ )}
</div>
);
}
diff --git a/client/src/pages/MeatSpace.jsx b/client/src/pages/MeatSpace.jsx
index bbce4e3293..b75ae4828a 100644
--- a/client/src/pages/MeatSpace.jsx
+++ b/client/src/pages/MeatSpace.jsx
@@ -7,6 +7,7 @@ import OverviewTab from '../components/meatspace/tabs/OverviewTab';
import AlcoholTab from '../components/meatspace/tabs/AlcoholTab';
import BloodTab from '../components/meatspace/tabs/BloodTab';
import GenomeTab from '../components/meatspace/tabs/GenomeTab';
+import HealthTab from '../components/meatspace/tabs/HealthTab';
import LifestyleTab from '../components/meatspace/tabs/LifestyleTab';
export default function MeatSpace() {
@@ -28,6 +29,8 @@ export default function MeatSpace() {
return <BloodTab />;
case 'genome':
return <GenomeTab />;
+ case 'health':
+ return <HealthTab />;
case 'lifestyle':
return <LifestyleTab />;
default: