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

docs(03-apple-health-integration): create phase plan

Adam Eivya6daeb93b23f
diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md
index 8c35af7774..76d77a58bb 100644
--- a/.planning/ROADMAP.md
+++ b/.planning/ROADMAP.md
@@ -58,11 +58,12 @@ Plans:
2. Bulk Apple Health XML export (500MB+) imports without OOM via streaming SAX parser, with progress reported via WebSocket
3. MeatSpace dashboard shows cards for steps, heart rate, sleep, and HRV trends from ingested data
4. Apple Health data correlates with existing MeatSpace data (alcohol vs HRV, activity vs blood work)
-**Plans**: TBD
+**Plans**: 3 plans
Plans:
-- [ ] 03-01: TBD
-- [ ] 03-02: TBD
+- [ ] 03-01-PLAN.md -- Backend foundation: Zod validation, JSON ingest with dedup, day-partitioned storage, query service, REST routes, client API functions (HLT-01, HLT-02)
+- [ ] 03-02-PLAN.md -- SAX streaming XML import with WebSocket progress, multer diskStorage upload, Import tab XML file picker UI (HLT-03, HLT-04)
+- [ ] 03-03-PLAN.md -- MeatSpace Health tab with steps/HR/sleep/HRV cards, range selector, alcohol-HRV and activity-blood correlation charts (HLT-05, HLT-06)
### Phase 4: Cross-Domain Insights Engine
**Goal**: PortOS surfaces actionable cross-domain patterns by correlating genome markers with health data and taste preferences with identity themes
@@ -103,6 +104,6 @@ Note: Phases 1 and 2 have no dependency on each other and can execute in paralle
|-------|----------------|--------|-----------|
| 1. Genome Migration Cleanup | 1/1 | Complete | 2026-02-26 |
| 2. Data Backup & Recovery | 2/2 | Complete | 2026-02-26 |
-| 3. Apple Health Integration | 0/2 | Not started | - |
+| 3. Apple Health Integration | 0/3 | Not started | - |
| 4. Cross-Domain Insights Engine | 0/2 | Not started | - |
| 5. Unified Search (Cmd+K) | 0/1 | Not started | - |
diff --git a/.planning/phases/03-apple-health-integration/03-01-PLAN.md b/.planning/phases/03-apple-health-integration/03-01-PLAN.md
new file mode 100644
index 0000000000..dbb91dbb8d
--- /dev/null
+++ b/.planning/phases/03-apple-health-integration/03-01-PLAN.md
@@ -0,0 +1,312 @@
+---
+phase: 03-apple-health-integration
+plan: 01
+type: execute
+wave: 1
+depends_on: []
+files_modified:
+ - server/lib/appleHealthValidation.js
+ - server/services/appleHealthIngest.js
+ - server/services/appleHealthQuery.js
+ - server/routes/appleHealth.js
+ - server/lib/fileUtils.js
+ - server/index.js
+ - client/src/services/api.js
+autonomous: true
+requirements:
+ - HLT-01
+ - HLT-02
+
+must_haves:
+ truths:
+ - "POST /api/apple-health/ingest accepts Health Auto Export JSON, validates with Zod, and returns success with record counts"
+ - "Duplicate records (same metric name + timestamp) are silently skipped on re-ingest"
+ - "Health data is persisted to day-partitioned files at data/health/YYYY-MM-DD.json"
+ - "GET /api/apple-health/metrics returns aggregated metric data for a requested date range"
+ artifacts:
+ - path: "server/lib/appleHealthValidation.js"
+ provides: "Zod schemas for Health Auto Export JSON ingest payload"
+ exports: ["healthIngestSchema"]
+ - path: "server/services/appleHealthIngest.js"
+ provides: "JSON ingest, dedup, day-file merge logic"
+ exports: ["ingestHealthData"]
+ - path: "server/services/appleHealthQuery.js"
+ provides: "Date-range queries for health metrics"
+ exports: ["getMetrics", "getMetricSummary", "getAvailableDateRange"]
+ - path: "server/routes/appleHealth.js"
+ provides: "REST endpoints for ingest and query"
+ exports: ["default (router)"]
+ key_links:
+ - from: "server/routes/appleHealth.js"
+ to: "server/services/appleHealthIngest.js"
+ via: "ingestHealthData(payload)"
+ pattern: "ingestHealthData"
+ - from: "server/routes/appleHealth.js"
+ to: "server/services/appleHealthQuery.js"
+ via: "getMetrics(metricName, from, to)"
+ pattern: "getMetrics"
+ - from: "server/index.js"
+ to: "server/routes/appleHealth.js"
+ via: "app.use('/api/apple-health', appleHealthRoutes)"
+ pattern: "appleHealthRoutes"
+---
+
+<objective>
+Build the Apple Health data ingest pipeline: Zod validation for Health Auto Export JSON, deduplication by metric+timestamp, day-partitioned file storage at `data/health/YYYY-MM-DD.json`, and query service for reading metrics by date range.
+
+Purpose: Creates the data foundation that both XML import (Plan 03-02) and dashboard cards (Plan 03-03) depend on.
+Output: Working REST API at `/api/apple-health/ingest` and `/api/apple-health/metrics`, data persisted to day-partitioned files.
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
[email protected]/phases/03-apple-health-integration/03-RESEARCH.md
+
+@server/lib/fileUtils.js — PATHS constants, readJSONFile, ensureDir
+@server/lib/meatspaceValidation.js — Zod schema patterns
+@server/routes/backup.js — Route pattern with asyncHandler, io access
+@server/services/meatspaceAlcohol.js — Service patterns (pure functions, file read/write)
+@server/index.js — Route registration pattern
+
+<interfaces>
+<!-- Key types and contracts the executor needs. Extracted from codebase. -->
+
+From server/lib/fileUtils.js:
+```javascript
+export const PATHS = {
+ root: join(__lib_dirname, '../..'),
+ data: join(__lib_dirname, '../../data'),
+ meatspace: join(__lib_dirname, '../../data/meatspace')
+ // ... health needs to be added here
+};
+export async function ensureDir(dir) { ... }
+export async function readJSONFile(filePath, defaultValue) { ... }
+```
+
+From server/lib/errorHandler.js:
+```javascript
+export function asyncHandler(fn) { ... }
+export class ServerError extends Error { ... }
+```
+
+From server/lib/validation.js:
+```javascript
+export function validateRequest(schema, data) { ... }
+```
+
+Health Auto Export JSON schema (from research):
+```json
+{
+ "data": {
+ "metrics": [
+ {
+ "name": "step_count",
+ "units": "count",
+ "data": [{ "qty": 8432, "date": "2024-01-15 08:30:00 -0800" }]
+ }
+ ]
+ }
+}
+```
+
+Day-partitioned file schema:
+```json
+{
+ "date": "2024-01-15",
+ "metrics": {
+ "step_count": [
+ { "date": "2024-01-15 08:30:00 -0800", "qty": 4211, "unit": "count" }
+ ]
+ },
+ "updated": "2024-01-16T10:00:00.000Z"
+}
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Create validation schemas, ingest service, and day-partitioned storage</name>
+ <files>
+ server/lib/appleHealthValidation.js
+ server/services/appleHealthIngest.js
+ server/lib/fileUtils.js
+ </files>
+ <action>
+**1. Add PATHS.health to fileUtils.js:**
+
+In `server/lib/fileUtils.js`, add to the PATHS object:
+```javascript
+health: join(__lib_dirname, '../../data/health'),
+```
+Place it alphabetically between `digitalTwin` and `memory`.
+
+**2. Create server/lib/appleHealthValidation.js:**
+
+Zod schemas following the meatspaceValidation.js pattern:
+
+- `healthDataPointSchema`: Object with `date` (string, required), `qty` (number, optional), `Min`/`Avg`/`Max` (number, optional for heart rate), `totalSleep`/`deep`/`rem`/`core`/`awake` (number, optional for sleep). Use `.passthrough()` to allow future fields from app updates.
+
+- `healthMetricSchema`: Object with `name` (string, min 1), `units` (string, optional), `data` (array of healthDataPointSchema).
+
+- `healthIngestSchema`: Object with `data` (object containing `metrics` array of healthMetricSchema, defaulting to `[]`, and `workouts` array of `z.unknown()`, defaulting to `[]`). Use `.passthrough()` on the `data` object to allow future Health Auto Export fields.
+
+Export all three schemas.
+
+**3. Create server/services/appleHealthIngest.js:**
+
+Pure functions + file I/O service:
+
+- `extractDateStr(dateString)`: Extract YYYY-MM-DD from Apple Health timestamp string. Use `dateString.substring(0, 10)` (not Date parsing) to avoid timezone conversion issues per research pitfall 5. Validate with regex `/^\d{4}-\d{2}-\d{2}$/`. Return null for invalid dates.
+
+- `dedupKey(metricName, dateString)`: Return `${metricName}::${dateString}` for dedup comparisons.
+
+- `readDayFile(dateStr)`: Read `join(PATHS.health, dateStr + '.json')` using `readJSONFile` with default `{ date: dateStr, metrics: {} }`.
+
+- `writeDayFile(dateStr, data)`: Ensure PATHS.health dir exists, set `data.updated = new Date().toISOString()`, write JSON with 2-space indent.
+
+- `mergeIntoDay(dateStr, metricName, newPoints)`: Load existing day file, build Set of existing date strings for that metric, filter new points to only those not already present, append unique points, write day file. Return count of new unique points added.
+
+- `ingestHealthData(payload)`: Main entry point. Iterate `payload.data.metrics`. For each metric, group its `data` points by extracted date string (skip points with null/invalid date). For each day group, call `mergeIntoDay`. Accumulate totals. Return `{ metricsProcessed, recordsIngested, recordsSkipped (dupes), daysAffected }`. Log with emoji prefix: `console.log('🍎 Health ingest: ${recordsIngested} records across ${daysAffected} days')`.
+
+**Important:** All metric types from the payload are stored (not just the core four). The decision locks "import ALL Apple Health metric types."
+ </action>
+ <verify>
+ <automated>cd server && node -e "import('./lib/appleHealthValidation.js').then(m => { const r = m.healthIngestSchema.safeParse({ data: { metrics: [{ name: 'step_count', units: 'count', data: [{ date: '2024-01-15 08:30:00 -0800', qty: 100 }] }] } }); console.log(r.success ? 'PASS' : 'FAIL: ' + JSON.stringify(r.error.issues)); })"</automated>
+ </verify>
+ <done>
+ - healthIngestSchema validates Health Auto Export JSON format with passthrough for future fields
+ - extractDateStr correctly pulls YYYY-MM-DD from timestamp strings without timezone conversion
+ - mergeIntoDay deduplicates by metric name + date string, skipping existing records
+ - Day files written to data/health/YYYY-MM-DD.json with correct schema
+ - PATHS.health added to fileUtils.js
+ </done>
+</task>
+
+<task type="auto">
+ <name>Task 2: Create query service, REST routes, and client API functions</name>
+ <files>
+ server/services/appleHealthQuery.js
+ server/routes/appleHealth.js
+ server/index.js
+ client/src/services/api.js
+ </files>
+ <action>
+**1. Create server/services/appleHealthQuery.js:**
+
+Query functions for reading health data:
+
+- `listDayFiles()`: Read the `PATHS.health` directory, return sorted array of date strings (from filenames without .json extension). Handle dir not existing (return `[]`).
+
+- `getAvailableDateRange()`: Call `listDayFiles()`, return `{ from: firstDate, to: lastDate, totalDays }` or null if no files.
+
+- `getMetrics(metricName, from, to)`: Read day files in the date range. For each day file, extract the metric's data array. Return flat array of all data points across the range, sorted by date. If `from`/`to` not provided, default to last 7 days.
+
+- `getMetricSummary(metricName, from, to)`: Call `getMetrics`, then compute summary stats: `count`, `latest` (most recent data point), `average` (of `qty` values if present, or `Avg` for heart rate). Return `{ metricName, count, latest, average, from, to, dataPoints }`.
+
+- `getDailyAggregates(metricName, from, to)`: Group data points by day and aggregate. For `step_count`: sum `qty` per day. For `heart_rate`: average of `Avg` values per day. For `heart_rate_variability_sdnn`: average `qty` per day. For `sleep_analysis`: take `totalSleep` directly. For all others: average `qty`. Return array of `{ date, value }` objects.
+
+- `getCorrelationData(from, to)`: Read health metrics AND alcohol data (import `getDailyAlcohol` from `meatspaceAlcohol.js`) for the date range. Build daily records with: `{ date, hrv, alcoholGrams, steps }`. Return the merged array. Also read blood tests (import `getBloodTests` from `meatspaceHealth.js`) for activity-blood correlation. Return `{ dailyData, bloodTests }`.
+
+**2. Create server/routes/appleHealth.js:**
+
+Following backup.js route pattern with asyncHandler:
+
+- `POST /ingest`: Validate body with `healthIngestSchema` using `validateRequest`. Call `ingestHealthData(validated)`. Return result object.
+
+- `GET /metrics/:metricName`: Query params `from`, `to` (optional strings). Call `getMetricSummary(metricName, from, to)`. Return summary.
+
+- `GET /metrics/:metricName/daily`: Query params `from`, `to`. Call `getDailyAggregates(metricName, from, to)`. Return array.
+
+- `GET /range`: Call `getAvailableDateRange()`. Return range object.
+
+- `GET /correlation`: Query params `from`, `to`. Call `getCorrelationData(from, to)`. Return correlation data.
+
+Export default router.
+
+**3. Register routes in server/index.js:**
+
+Add import at top (alphabetical with other route imports):
+```javascript
+import appleHealthRoutes from './routes/appleHealth.js';
+```
+
+Add route registration (before `/api/meatspace` to avoid path conflicts):
+```javascript
+app.use('/api/apple-health', appleHealthRoutes);
+```
+
+**4. Add client API functions in client/src/services/api.js:**
+
+Add a new section "// Apple Health" (alphabetical placement, near the top after "// Apps"):
+
+```javascript
+// Apple Health
+export const ingestAppleHealth = (data) => request('/apple-health/ingest', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const getAppleHealthMetrics = (metricName, from, to) => {
+ const params = new URLSearchParams();
+ if (from) params.set('from', from);
+ if (to) params.set('to', to);
+ return request(`/apple-health/metrics/${metricName}/daily?${params}`);
+};
+export const getAppleHealthSummary = (metricName, from, to) => {
+ const params = new URLSearchParams();
+ if (from) params.set('from', from);
+ if (to) params.set('to', to);
+ return request(`/apple-health/metrics/${metricName}?${params}`);
+};
+export const getAppleHealthRange = () => request('/apple-health/range');
+export const getAppleHealthCorrelation = (from, to) => {
+ const params = new URLSearchParams();
+ if (from) params.set('from', from);
+ if (to) params.set('to', to);
+ return request(`/apple-health/correlation?${params}`);
+};
+```
+ </action>
+ <verify>
+ <automated>cd server && node -e "import('./routes/appleHealth.js').then(m => console.log(m.default ? 'PASS: router exported' : 'FAIL'))" && node -e "import('./services/appleHealthQuery.js').then(m => console.log(typeof m.getMetrics === 'function' && typeof m.getDailyAggregates === 'function' ? 'PASS' : 'FAIL'))"</automated>
+ </verify>
+ <done>
+ - GET /api/apple-health/metrics/:metricName returns metric summary for date range
+ - GET /api/apple-health/metrics/:metricName/daily returns daily aggregated values
+ - GET /api/apple-health/range returns available data date range
+ - GET /api/apple-health/correlation returns merged HRV+alcohol+steps+blood data
+ - POST /api/apple-health/ingest validates and persists Health Auto Export JSON
+ - Route registered in index.js at /api/apple-health
+ - Client API functions added for all endpoints
+ </done>
+</task>
+
+</tasks>
+
+<verification>
+1. `cd server && node -e "import('./lib/appleHealthValidation.js').then(m => console.log('validation OK'))"` -- validation module loads
+2. `cd server && node -e "import('./services/appleHealthIngest.js').then(m => console.log('ingest OK'))"` -- ingest service loads
+3. `cd server && node -e "import('./services/appleHealthQuery.js').then(m => console.log('query OK'))"` -- query service loads
+4. `cd server && node -e "import('./routes/appleHealth.js').then(m => console.log('routes OK'))"` -- routes load
+5. `cd server && npm test` -- all existing tests pass (no regressions)
+</verification>
+
+<success_criteria>
+- POST /api/apple-health/ingest accepts Health Auto Export JSON and returns record counts
+- Duplicate records are silently skipped on re-ingest
+- Data persists to data/health/YYYY-MM-DD.json files
+- Query service returns aggregated metrics for date ranges
+- All existing tests pass
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/03-apple-health-integration/03-01-SUMMARY.md`
+</output>
diff --git a/.planning/phases/03-apple-health-integration/03-02-PLAN.md b/.planning/phases/03-apple-health-integration/03-02-PLAN.md
new file mode 100644
index 0000000000..73560934fe
--- /dev/null
+++ b/.planning/phases/03-apple-health-integration/03-02-PLAN.md
@@ -0,0 +1,352 @@
+---
+phase: 03-apple-health-integration
+plan: 02
+type: execute
+wave: 2
+depends_on:
+ - 03-01
+files_modified:
+ - server/services/appleHealthXml.js
+ - server/routes/appleHealth.js
+ - client/src/components/meatspace/tabs/ImportTab.jsx
+autonomous: false
+requirements:
+ - HLT-03
+ - HLT-04
+
+must_haves:
+ truths:
+ - "Uploading a 500MB+ Apple Health XML export completes without OOM errors"
+ - "XML import progress (record count) updates in real-time via WebSocket during import"
+ - "XML records are normalized to the same day-file format as JSON ingest (metric names mapped from HK identifiers)"
+ - "Sleep XML records with categorical values are correctly parsed into duration-based stage data"
+ - "Import tab shows a working file picker and progress bar for Apple Health XML upload"
+ artifacts:
+ - path: "server/services/appleHealthXml.js"
+ provides: "SAX streaming XML parser for Apple Health exports"
+ exports: ["importAppleHealthXml"]
+ - path: "server/routes/appleHealth.js"
+ provides: "POST /import/xml endpoint with multer diskStorage"
+ contains: "upload.single"
+ - path: "client/src/components/meatspace/tabs/ImportTab.jsx"
+ provides: "XML file picker with WebSocket progress bar"
+ contains: "health:xml:progress"
+ key_links:
+ - from: "server/routes/appleHealth.js"
+ to: "server/services/appleHealthXml.js"
+ via: "importAppleHealthXml(filePath, io)"
+ pattern: "importAppleHealthXml"
+ - from: "client/src/components/meatspace/tabs/ImportTab.jsx"
+ to: "socket.io client"
+ via: "socket.on('health:xml:progress')"
+ pattern: "health:xml:progress"
+ - from: "server/services/appleHealthXml.js"
+ to: "server/services/appleHealthIngest.js"
+ via: "readDayFile/writeDayFile for persistence"
+ pattern: "writeDayFile"
+---
+
+<objective>
+Build the streaming XML import pipeline for bulk Apple Health exports (500MB+) using SAX parsing, and update the Import tab with a working file picker and real-time WebSocket progress bar.
+
+Purpose: Enables importing years of historical Apple Health data from iOS exports without memory issues.
+Output: Working XML upload at POST /api/apple-health/import/xml, real-time progress in Import tab.
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
[email protected]/phases/03-apple-health-integration/03-RESEARCH.md
[email protected]/phases/03-apple-health-integration/03-01-SUMMARY.md
+
+@server/services/appleHealthIngest.js — readDayFile, writeDayFile from Plan 03-01
+@server/routes/appleHealth.js — Existing routes from Plan 03-01
+@server/routes/backup.js — io.emit WebSocket pattern
+@client/src/components/meatspace/tabs/ImportTab.jsx — Existing import tab with Apple Health placeholder
+@client/src/services/socket.js — Socket.io client
+
+<interfaces>
+<!-- From Plan 03-01 (will exist by execution time) -->
+
+From server/services/appleHealthIngest.js:
+```javascript
+export async function readDayFile(dateStr) { ... }
+export async function writeDayFile(dateStr, data) { ... }
+export function extractDateStr(dateString) { ... }
+```
+
+From server/routes/appleHealth.js:
+```javascript
+// Router with existing POST /ingest and GET endpoints
+// Add POST /import/xml to this same router
+```
+
+WebSocket pattern (from backup.js):
+```javascript
+const io = req.app.get('io');
+// Service emits: io.emit('health:xml:progress', { processed, total })
+// Service emits: io.emit('health:xml:complete', { days, records })
+```
+
+Apple Health XML Record structure:
+```xml
+<Record type="HKQuantityTypeIdentifierStepCount" value="432" startDate="2024-01-15 10:00:00 -0800" endDate="..." unit="count" sourceName="iPhone"/>
+<Record type="HKCategoryTypeIdentifierSleepAnalysis" value="HKCategoryValueSleepAnalysisAsleepDeep" startDate="..." endDate="..."/>
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Create SAX XML streaming service and add XML import route</name>
+ <files>
+ server/services/appleHealthXml.js
+ server/routes/appleHealth.js
+ </files>
+ <action>
+**Install dependencies first:**
+```bash
+cd server && npm install sax multer
+```
+
+**1. Create server/services/appleHealthXml.js:**
+
+Streaming SAX XML parser for Apple Health exports. Key components:
+
+**XML-to-metric name mapping:**
+```javascript
+const XML_TO_METRIC_NAME = {
+ 'HKQuantityTypeIdentifierStepCount': 'step_count',
+ 'HKQuantityTypeIdentifierHeartRate': 'heart_rate',
+ 'HKQuantityTypeIdentifierHeartRateVariabilitySDNN': 'heart_rate_variability_sdnn',
+ 'HKCategoryTypeIdentifierSleepAnalysis': 'sleep_analysis',
+ // All other types: store with original HK identifier (lowercase normalized)
+};
+```
+
+**Sleep stage mapping:**
+```javascript
+const SLEEP_STAGE_MAP = {
+ 'HKCategoryValueSleepAnalysisAsleepDeep': 'deep',
+ 'HKCategoryValueSleepAnalysisAsleepREM': 'rem',
+ 'HKCategoryValueSleepAnalysisAsleepCore': 'core',
+ 'HKCategoryValueSleepAnalysisAwake': 'awake',
+ 'HKCategoryValueSleepAnalysisInBed': 'inBed',
+ 'HKCategoryValueSleepAnalysisAsleep': 'asleep' // Legacy pre-iOS 16
+};
+```
+
+**`normalizeXmlRecord(node)`:** Pure function. Takes SAX opentag node with attributes. Returns `{ metricName, dateStr, dataPoint }` or null for invalid records.
+
+- Extract `type`, `value`, `startdate`, `enddate`, `unit`, `sourcename` from `node.attributes` (lowercase because `sax.createStream(false, { lowercase: true })`).
+- Map `type` via `XML_TO_METRIC_NAME`, falling back to lowercase type string for unknown types.
+- Extract dateStr using `extractDateStr(startdate)` from appleHealthIngest.js. Return null if invalid.
+- For sleep analysis (`type === 'hkcategorytypeidentifiersleepanalysis'` — lowercase): Calculate duration in hours from `(new Date(enddate) - new Date(startdate)) / 3600000`. Map `value` via `SLEEP_STAGE_MAP`. Create data point with `{ date: startdate, stage: mappedStage, durationHours: duration }`.
+- For numeric types: Create data point with `{ date: startdate, qty: parseFloat(value), unit: unit ?? null, src: sourcename ?? null }`. If `type` is heart rate, also add `end: enddate`.
+- Skip records where `startdate` is missing.
+
+**`importAppleHealthXml(filePath, io = null)`:** Main export.
+
+- Create `sax.createStream(false, { lowercase: true })` (non-strict mode per research pitfall 1).
+- Accumulate records into `dayBuckets = {}` keyed by dateStr, then by metricName.
+- On `opentag`: If `node.name !== 'record'`, return. Call `normalizeXmlRecord(node)`. If result is null, skip. Accumulate into dayBuckets. Increment `processedRecords`. Every 10000 records, emit `io.emit('health:xml:progress', { processed: processedRecords })` and log `console.log('🍎 XML import progress: ${processedRecords} records')`.
+- On `error`: Clear `this._parser.error = null`, call `this._parser.resume()` (per research pitfall 1 — Apple Health XML can have minor malformations). Log error with `console.error('❌ XML parse error at record ${processedRecords}: ${e.message}')`.
+- Pipe `createReadStream(filePath)` to saxStream. Await stream end via Promise.
+- **After parsing completes:** For step_count in dayBuckets, aggregate: sum all `qty` values per day into a single entry (per research pitfall 3). For sleep_analysis, aggregate stage durations per day into a single summary: `{ date, totalSleep, deep, rem, core, awake }` (sum durations by stage).
+- Write all day files sequentially (not during SAX event loop — per research pitfall 7). For each dateStr in dayBuckets: read existing day file, merge new metrics (dedup by date string within each metric), write back.
+- Delete temp file: `unlink(filePath, () => {})`.
+- Emit `io.emit('health:xml:complete', { days: Object.keys(dayBuckets).length, records: processedRecords })`.
+- Log `console.log('🍎 XML import complete: ${processedRecords} records across ${days} days')`.
+- Return `{ days: daysCount, records: processedRecords }`.
+
+Export `normalizeXmlRecord` (for testing) and `importAppleHealthXml`.
+
+**2. Add XML import route to server/routes/appleHealth.js:**
+
+At the top of the file, add imports:
+```javascript
+import multer from 'multer';
+import { tmpdir } from 'os';
+import { importAppleHealthXml } from '../services/appleHealthXml.js';
+```
+
+Configure multer with diskStorage (NOT memoryStorage — per research, avoids OOM on 500MB files):
+```javascript
+const upload = multer({
+ storage: multer.diskStorage({
+ destination: (req, file, cb) => cb(null, tmpdir()),
+ filename: (req, file, cb) => cb(null, `apple-health-${Date.now()}.xml`)
+ }),
+ limits: { fileSize: 2 * 1024 * 1024 * 1024 }, // 2GB max
+ fileFilter: (req, file, cb) => {
+ if (file.mimetype === 'text/xml' || file.mimetype === 'application/xml' || file.originalname.endsWith('.xml')) {
+ cb(null, true);
+ } else {
+ cb(new ServerError('Only XML files are accepted', 400));
+ }
+ }
+});
+```
+
+Add route:
+```javascript
+// POST /api/apple-health/import/xml
+router.post('/import/xml', upload.single('file'), asyncHandler(async (req, res) => {
+ const io = req.app.get('io');
+ const filePath = req.file?.path;
+ if (!filePath) throw new ServerError('No file uploaded', 400);
+ const result = await importAppleHealthXml(filePath, io);
+ res.json(result);
+}));
+```
+ </action>
+ <verify>
+ <automated>cd server && node -e "import('./services/appleHealthXml.js').then(m => console.log(typeof m.importAppleHealthXml === 'function' && typeof m.normalizeXmlRecord === 'function' ? 'PASS' : 'FAIL'))"</automated>
+ </verify>
+ <done>
+ - SAX streaming parser handles Apple Health XML without loading file into memory
+ - XML metric types mapped to normalized metric names matching JSON ingest format
+ - Sleep categorical values parsed into duration-based stage data
+ - Step counts aggregated per day (not raw sensor readings)
+ - Non-strict SAX mode handles malformed XML gracefully
+ - WebSocket progress emitted every 10000 records
+ - Temp file cleaned up after import
+ - POST /import/xml route uses multer diskStorage with 2GB limit
+ </done>
+</task>
+
+<task type="auto">
+ <name>Task 2: Update Import tab with Apple Health XML file picker and progress bar</name>
+ <files>
+ client/src/components/meatspace/tabs/ImportTab.jsx
+ client/src/services/api.js
+ </files>
+ <action>
+**1. Add XML upload API function in client/src/services/api.js:**
+
+Add to the "// Apple Health" section (created in Plan 03-01):
+```javascript
+export const uploadAppleHealthXml = (file) => {
+ const formData = new FormData();
+ formData.append('file', file);
+ return fetch(`${API_BASE}/apple-health/import/xml`, {
+ method: 'POST',
+ body: formData
+ // No Content-Type header — browser sets multipart boundary automatically
+ }).then(async res => {
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({ error: res.statusText }));
+ throw new Error(err.error || res.statusText);
+ }
+ return res.json();
+ });
+};
+```
+
+Note: This uses `fetch` directly instead of the `request` helper because `request` sets `Content-Type: application/json` which conflicts with `multipart/form-data`. The FormData upload needs the browser to set the Content-Type with the correct boundary.
+
+**2. Replace the Apple Health placeholder in ImportTab.jsx:**
+
+Remove the disabled placeholder section (the `<div>` with `opacity-60` and "Coming soon" text, lines ~134-143 of current file).
+
+Replace with a working Apple Health XML import section:
+
+- Import `socket` from `'../../../services/socket'` and `uploadAppleHealthXml` from api.
+- Add state: `xmlImporting`, `xmlProgress`, `xmlResult`, `xmlError`, `xmlFileName`.
+- Add `xmlFileInputRef` useRef.
+- Add useEffect for WebSocket listeners:
+ ```javascript
+ useEffect(() => {
+ const onProgress = ({ processed }) => setXmlProgress(processed);
+ const onComplete = (result) => { setXmlResult(result); setXmlImporting(false); };
+ socket.on('health:xml:progress', onProgress);
+ socket.on('health:xml:complete', onComplete);
+ return () => {
+ socket.off('health:xml:progress', onProgress);
+ socket.off('health:xml:complete', onComplete);
+ };
+ }, []);
+ ```
+- Add `handleXmlFileSelect` handler: Get file from input, validate `.xml` extension, set `xmlImporting(true)`, `xmlProgress(0)`, clear errors/results, call `uploadAppleHealthXml(file)`. On error, set xmlError. On success, result comes via WebSocket `onComplete`.
+
+UI structure (matching the existing TSV import card style):
+- Card with `bg-port-card border border-port-border rounded-xl p-6`.
+- Header: Apple icon (use `Upload` from lucide, or `Apple` if available — check lucide-react; if not, use `HeartPulse`) + "Apple Health XML Import" in uppercase tracking-wider.
+- Description: "Import your Apple Health export. On your iPhone: Settings > Health > Export All Health Data. Extract the ZIP and select the export.xml file."
+- Instruction note: "Extract the ZIP file first — upload the export.xml file directly."
+- File picker button: Same style as TSV button. Accepts `.xml` files only.
+- During import: Show progress bar with `bg-port-accent` fill and record count text: "{xmlProgress.toLocaleString()} records processed". Use a pulsing/animated progress bar since total count is unknown (indeterminate style with the record count as text).
+- On complete: Show success card with days and records counts (matching TSV success card style).
+- On error: Show error card (matching TSV error card style).
+ </action>
+ <verify>
+ <automated>cd server && npm test</automated>
+ </verify>
+ <done>
+ - Apple Health placeholder replaced with working XML file picker
+ - File picker accepts .xml files only
+ - Progress bar shows live record count during import via WebSocket
+ - Success state shows days and records imported
+ - Error state displays error message
+ - Import follows existing TSV import card styling
+ - Instructions tell user to extract ZIP and upload export.xml
+ </done>
+</task>
+
+<task type="checkpoint:human-verify" gate="blocking">
+ <name>Task 3: Verify XML import and ingest pipeline</name>
+ <files>none (verification only)</files>
+ <action>
+Human verification checkpoint. Verify:
+1. The Import tab shows the Apple Health XML Import section (replacing the old placeholder)
+2. The file picker accepts only .xml files
+3. POST /api/apple-health/ingest works with curl test data
+4. Day-partitioned files are created in data/health/
+5. Dedup works on repeated ingest
+ </action>
+ <verify>
+ <automated>curl -s -X POST http://localhost:5554/api/apple-health/ingest -H 'Content-Type: application/json' -d '{"data":{"metrics":[{"name":"step_count","units":"count","data":[{"date":"2024-01-15 08:30:00 -0800","qty":8432}]}]}}' | node -e "process.stdin.on('data',d=>{const r=JSON.parse(d);console.log(r.recordsIngested>0?'PASS':'FAIL')})"</automated>
+ </verify>
+ <done>XML import pipeline and JSON ingest verified end-to-end, Import tab UI confirmed</done>
+ <what-built>Apple Health XML import pipeline with streaming SAX parser, WebSocket progress, and Import tab UI</what-built>
+ <how-to-verify>
+ 1. Navigate to MeatSpace page and find the Import tab (check if it is accessible from the Lifestyle tab or a separate import section)
+ 2. Verify the Apple Health XML Import section replaces the old placeholder
+ 3. Verify the file picker only accepts .xml files
+ 4. If you have an Apple Health export.xml available, test importing it. Otherwise, verify the UI renders correctly with proper styling.
+ 5. Verify `curl -X POST http://localhost:5554/api/apple-health/ingest -H 'Content-Type: application/json' -d '{"data":{"metrics":[{"name":"step_count","units":"count","data":[{"date":"2024-01-15 08:30:00 -0800","qty":8432}]}]}}'` returns success with recordsIngested count
+ 6. Verify `ls data/health/` shows `2024-01-15.json` was created
+ 7. Re-run the same curl command and verify `recordsSkipped` increases (dedup working)
+ </how-to-verify>
+ <resume-signal>Type "approved" or describe issues</resume-signal>
+</task>
+
+</tasks>
+
+<verification>
+1. `npm install` in server completes with `sax` and `multer` added to package.json
+2. POST /api/apple-health/ingest accepts and persists Health Auto Export JSON
+3. POST /api/apple-health/import/xml accepts XML upload via multipart form
+4. Import tab shows Apple Health XML import section with progress bar
+5. `cd server && npm test` — all existing tests pass
+</verification>
+
+<success_criteria>
+- Apple Health XML files (500MB+) can be imported without OOM via SAX streaming
+- Import progress updates in real-time via WebSocket (record count every 10k records)
+- XML metric types are normalized to match JSON ingest metric names
+- Sleep XML categorical values are correctly converted to duration data
+- Import tab has working file picker replacing the disabled placeholder
+- All existing tests pass
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/03-apple-health-integration/03-02-SUMMARY.md`
+</output>
diff --git a/.planning/phases/03-apple-health-integration/03-03-PLAN.md b/.planning/phases/03-apple-health-integration/03-03-PLAN.md
new file mode 100644
index 0000000000..34efe6a9a1
--- /dev/null
+++ b/.planning/phases/03-apple-health-integration/03-03-PLAN.md
@@ -0,0 +1,360 @@
+---
+phase: 03-apple-health-integration
+plan: 03
+type: execute
+wave: 2
+depends_on:
+ - 03-01
+files_modified:
+ - client/src/components/meatspace/constants.js
+ - client/src/components/meatspace/tabs/HealthTab.jsx
+ - client/src/components/meatspace/StepsCard.jsx
+ - client/src/components/meatspace/HeartRateCard.jsx
+ - client/src/components/meatspace/SleepCard.jsx
+ - client/src/components/meatspace/HrvCard.jsx
+ - client/src/components/meatspace/AlcoholHrvCorrelation.jsx
+ - client/src/components/meatspace/ActivityBloodCorrelation.jsx
+ - client/src/pages/MeatSpace.jsx
+autonomous: false
+requirements:
+ - HLT-05
+ - HLT-06
+
+must_haves:
+ truths:
+ - "MeatSpace has a Health tab showing steps, heart rate, sleep, and HRV cards with trend charts"
+ - "Each health card shows a hero number (current/average) and line chart trend for the selected range"
+ - "Range selector buttons (7d/30d/90d/1y) filter all health cards consistently"
+ - "Sleep card shows total hours as hero and stacked horizontal bar for stage proportions"
+ - "Alcohol vs HRV dual-axis chart shows correlation with auto-generated text summary"
+ - "Activity vs blood work chart shows 30-day rolling average steps alongside blood markers"
+ - "Correlations show minimum data threshold message when fewer than 14 days of data exist"
+ artifacts:
+ - path: "client/src/components/meatspace/tabs/HealthTab.jsx"
+ provides: "Health tab container with range selector and card grid"
+ contains: "HealthTab"
+ - path: "client/src/components/meatspace/StepsCard.jsx"
+ provides: "Steps trend card with hero number and LineChart"
+ contains: "StepsCard"
+ - path: "client/src/components/meatspace/HeartRateCard.jsx"
+ provides: "Heart rate card with avg/min/max"
+ contains: "HeartRateCard"
+ - path: "client/src/components/meatspace/SleepCard.jsx"
+ provides: "Sleep card with stacked horizontal bar"
+ contains: "SleepCard"
+ - path: "client/src/components/meatspace/HrvCard.jsx"
+ provides: "HRV trend card"
+ contains: "HrvCard"
+ - path: "client/src/components/meatspace/AlcoholHrvCorrelation.jsx"
+ provides: "Dual-axis correlation chart"
+ contains: "AlcoholHrvCorrelation"
+ - path: "client/src/components/meatspace/ActivityBloodCorrelation.jsx"
+ provides: "Activity vs blood work correlation"
+ contains: "ActivityBloodCorrelation"
+ key_links:
+ - from: "client/src/components/meatspace/tabs/HealthTab.jsx"
+ to: "/api/apple-health/metrics/:metricName/daily"
+ via: "api.getAppleHealthMetrics()"
+ pattern: "getAppleHealthMetrics"
+ - from: "client/src/components/meatspace/tabs/HealthTab.jsx"
+ to: "/api/apple-health/correlation"
+ via: "api.getAppleHealthCorrelation()"
+ pattern: "getAppleHealthCorrelation"
+ - from: "client/src/pages/MeatSpace.jsx"
+ to: "client/src/components/meatspace/tabs/HealthTab.jsx"
+ via: "case 'health' in renderTabContent"
+ pattern: "HealthTab"
+---
+
+<objective>
+Build the MeatSpace Health tab with four metric cards (steps, heart rate, sleep, HRV), time range selector, and two correlation charts (alcohol vs HRV, activity vs blood work) with auto-generated text summaries.
+
+Purpose: Makes ingested Apple Health data visible and actionable on the MeatSpace dashboard.
+Output: New Health tab in MeatSpace with trend charts and correlation insights.
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
[email protected]/phases/03-apple-health-integration/03-RESEARCH.md
[email protected]/phases/03-apple-health-integration/03-01-SUMMARY.md
+
+@client/src/components/meatspace/constants.js — TABS array, design tokens
+@client/src/components/meatspace/AlcoholChart.jsx — Recharts patterns for dark theme
+@client/src/components/meatspace/BloodTestCard.jsx — Card component patterns
+@client/src/pages/MeatSpace.jsx — Tab routing, renderTabContent switch
+@client/src/services/api.js — API functions from Plan 03-01
+
+<interfaces>
+<!-- From Plan 03-01 (will exist by execution time) -->
+
+From client/src/services/api.js:
+```javascript
+export const getAppleHealthMetrics = (metricName, from, to) => ...;
+export const getAppleHealthSummary = (metricName, from, to) => ...;
+export const getAppleHealthRange = () => ...;
+export const getAppleHealthCorrelation = (from, to) => ...;
+```
+
+API response shapes:
+```javascript
+// GET /api/apple-health/metrics/:metricName/daily
+[{ date: "2024-01-15", value: 8432 }, ...]
+
+// GET /api/apple-health/metrics/:metricName
+{ metricName, count, latest, average, from, to, dataPoints: [...] }
+
+// GET /api/apple-health/correlation
+{ dailyData: [{ date, hrv, alcoholGrams, steps }], bloodTests: [...] }
+```
+
+From constants.js:
+```javascript
+export const TABS = [
+ { id: 'overview', ... },
+ { id: 'alcohol', ... },
+ { id: 'blood', ... },
+ { id: 'genome', ... },
+ { id: 'lifestyle', ... }
+];
+```
+
+Recharts imports (already installed v3.7.0):
+```javascript
+import { LineChart, Line, BarChart, Bar, ComposedChart, XAxis, YAxis,
+ CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
+```
+
+Design tokens:
+```
+bg-port-card (#1a1a1a), border-port-border (#2a2a2a), text-port-accent (#3b82f6)
+CartesianGrid stroke="#2a2a2a", tick fill="#9ca3af" fontSize 11
+Tooltip: background '#1a1a1a', border '1px solid #2a2a2a', color '#fff'
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Create four health metric cards and HealthTab container</name>
+ <files>
+ client/src/components/meatspace/StepsCard.jsx
+ client/src/components/meatspace/HeartRateCard.jsx
+ client/src/components/meatspace/SleepCard.jsx
+ client/src/components/meatspace/HrvCard.jsx
+ client/src/components/meatspace/tabs/HealthTab.jsx
+ </files>
+ <action>
+**All four cards follow the same layout pattern (per locked decision):**
+- Card wrapper: `bg-port-card border border-port-border rounded-xl p-6`
+- Hero number at top: large text showing current/average value with unit label
+- Line chart trend below using recharts `ResponsiveContainer` + `LineChart`
+- Charts use dark theme tokens: CartesianGrid `stroke="#2a2a2a"`, tick `fill="#9ca3af" fontSize={11}`, Tooltip with dark background
+- Each card receives `data` (array of `{ date, value }`) and `loading` as props
+
+**1. StepsCard.jsx:**
+- Hero: Daily average steps for the range, formatted with `toLocaleString()` (e.g., "8,432")
+- Unit label: "avg daily steps"
+- Chart: LineChart with `dataKey="value"`, stroke `#3b82f6` (port-accent), dot={false}, strokeWidth 2
+- Empty state: "No step data available" in gray text
+
+**2. HeartRateCard.jsx:**
+- Hero: Average resting heart rate (use average of `value` field), with "bpm" unit
+- Chart: LineChart with `dataKey="value"`, stroke `#ef4444` (red/port-error for heart), dot={false}
+- Empty state: "No heart rate data available"
+
+**3. SleepCard.jsx:**
+- Hero: Average total sleep hours (e.g., "7.2 hrs")
+- Below hero: Stacked horizontal BarChart showing stage proportions for the most recent days. Use `BarChart layout="vertical"` with stacked Bars:
+ - deep: `#3b82f6` (blue)
+ - rem: `#8b5cf6` (purple)
+ - core: `#06b6d4` (cyan)
+ - awake: `#6b7280` (gray)
+- This card accepts `data` shaped as `[{ date, totalSleep, deep, rem, core, awake }]`
+- Only show last 7 days in the stacked bar (even if range is larger) to keep it readable
+- Empty state: "No sleep data available"
+
+**4. HrvCard.jsx:**
+- Hero: Average HRV in ms (e.g., "42 ms")
+- Chart: LineChart with `dataKey="value"`, stroke `#22c55e` (green/port-success), dot={false}
+- Empty state: "No HRV data available"
+
+**5. HealthTab.jsx:**
+- State: `range` (default `'7d'`), `stepsData`, `hrData`, `sleepData`, `hrvData`, `correlationData`, `loading`
+- Range selector: Row of buttons `7d`, `30d`, `90d`, `1y` (per locked decision). Active button highlighted with `bg-port-accent/10 text-port-accent`. Calculate `from` date string from range.
+- On mount and range change: Fetch all four metrics in parallel using `Promise.all([api.getAppleHealthMetrics('step_count', from, to), api.getAppleHealthMetrics('heart_rate', from, to), ...])`. Also fetch correlation data: `api.getAppleHealthCorrelation(from, to)`.
+- Layout: 2-column grid on lg, 1-column on mobile (`grid grid-cols-1 lg:grid-cols-2 gap-6`).
+ - Row 1: StepsCard, HeartRateCard
+ - Row 2: SleepCard, HrvCard
+ - Row 3 (full width): Correlations section (rendered by correlation components from Task 2)
+- Pass fetched data and loading state to each card.
+- Import correlation components (AlcoholHrvCorrelation, ActivityBloodCorrelation) — these will be created in Task 2. For now, conditionally render them only if `correlationData` exists. Pass `correlationData` and `range` as props.
+ </action>
+ <verify>
+ <automated>cd server && npm test</automated>
+ </verify>
+ <done>
+ - StepsCard shows hero average + LineChart trend
+ - HeartRateCard shows hero avg BPM + LineChart trend
+ - SleepCard shows hero avg hours + stacked horizontal BarChart for stages
+ - HrvCard shows hero avg ms + LineChart trend
+ - HealthTab fetches all metrics in parallel on range change
+ - Range selector buttons (7d/30d/90d/1y) control all cards consistently
+ - All cards have empty states for when no data exists
+ - Dark theme tokens used consistently across all charts
+ </done>
+</task>
+
+<task type="auto">
+ <name>Task 2: Create correlation charts and wire Health tab into MeatSpace</name>
+ <files>
+ client/src/components/meatspace/AlcoholHrvCorrelation.jsx
+ client/src/components/meatspace/ActivityBloodCorrelation.jsx
+ client/src/components/meatspace/constants.js
+ client/src/pages/MeatSpace.jsx
+ </files>
+ <action>
+**1. AlcoholHrvCorrelation.jsx:**
+
+Dual-axis overlay chart (per locked decision):
+- Receives `data` prop: `{ dailyData: [{ date, hrv, alcoholGrams }] }` and `range`
+- Minimum data threshold check: If `dailyData.length < 14`, show message "Need 14+ days of data for correlations -- {dailyData.length} days so far." in a subtle card with `text-gray-400`.
+- Chart: `ComposedChart` with two `YAxis`:
+ - Left YAxis (`yAxisId="hrv"`): HRV in ms, `orientation="left"`
+ - Right YAxis (`yAxisId="alcohol"`): Alcohol in grams, `orientation="right"`
+ - `Line` for HRV: `yAxisId="hrv"`, stroke `#22c55e` (green), dot={false}
+ - `Bar` for alcohol: `yAxisId="alcohol"`, fill `#f59e0b` (amber/port-warning), opacity 0.7
+- Card wrapper with title: "Alcohol vs HRV" with HeartPulse + Beer icons
+- **Auto-generated text summary below chart** (per locked decision — computed, NOT LLM):
+ ```
+ Calculate:
+ - drinkingDays = days where alcoholGrams > 0
+ - soberDays = days where alcoholGrams === 0
+ - avgHrvDrinking = average HRV on drinking days
+ - avgHrvSober = average HRV on sober days
+ - percentDiff = ((avgHrvSober - avgHrvDrinking) / avgHrvSober * 100).toFixed(0)
+
+ Display: "HRV averages {avgHrvDrinking}ms on drinking days vs {avgHrvSober}ms on sober days ({percentDiff}% difference)"
+ If no drinking days: "No alcohol data recorded in this period"
+ If no sober days: "No sober days recorded in this period"
+ ```
+- Dark theme styling matching other charts
+
+**2. ActivityBloodCorrelation.jsx:**
+
+Activity vs blood work chart (per locked decision):
+- Receives `data` prop: `{ dailyData: [{ date, steps }], bloodTests: [{ date, results: {...} }] }` and `range`
+- Minimum data threshold: Same 14-day check as alcohol correlation.
+- Calculate 30-day rolling average steps leading up to each blood test date:
+ ```javascript
+ For each blood test:
+ - Find the 30 days of dailyData before the blood test date
+ - Calculate average steps for those 30 days
+ - Pair with key blood markers from the test (use markers from the test results if available)
+ ```
+- Chart: `ComposedChart` showing:
+ - Bar for rolling average steps (`yAxisId="steps"`)
+ - Line/dots for key blood markers at test dates (`yAxisId="markers"`) — choose 2-3 most common markers (cholesterol, glucose, or whatever is in the blood test data)
+ - If no blood tests in range, show message: "No blood tests in this period to correlate with activity"
+- **Auto-generated text summary:** "Average {avgSteps} steps/day in the 30 days before your {testDate} blood test"
+- Card wrapper with title: "Activity vs Blood Work"
+- Wrap in `ResponsiveContainer`
+
+**3. Add Health tab to constants.js:**
+
+In the TABS array, add (alphabetically between 'genome' and 'lifestyle'):
+```javascript
+{ id: 'health', label: 'Health', icon: HeartPulse }
+```
+
+Note: HeartPulse is already imported in constants.js (used for Blood & Body). But 'health' uses it too. Since Blood & Body already uses HeartPulse, use a different icon for Health. Check available lucide-react icons: use `Activity` (already imported) for Health since it represents activity/vitals. Actually `Activity` is used for Overview. Use `Heart` from lucide-react instead — import it.
+
+Wait, looking at constants.js: `Activity` is used for Overview, `HeartPulse` for Blood & Body. For the Health tab, import and use `Stethoscope` from lucide-react — it's distinct and represents health monitoring.
+
+Update the import line to include `Stethoscope`.
+
+**4. Wire Health tab into MeatSpace.jsx:**
+
+Add import:
+```javascript
+import HealthTab from '../components/meatspace/tabs/HealthTab';
+```
+
+Add case to `renderTabContent` switch (alphabetically between 'genome' and 'lifestyle'):
+```javascript
+case 'health':
+ return <HealthTab />;
+```
+ </action>
+ <verify>
+ <automated>cd server && npm test</automated>
+ </verify>
+ <done>
+ - AlcoholHrvCorrelation shows dual-axis chart with auto-generated text summary
+ - ActivityBloodCorrelation shows activity vs blood markers with text summary
+ - Both correlations show minimum data threshold message when < 14 days
+ - Health tab appears in MeatSpace tab bar between Genome and Lifestyle
+ - Clicking Health tab renders HealthTab component via URL routing (/meatspace/health)
+ - All correlation text summaries are computed from data, not LLM-generated
+ </done>
+</task>
+
+<task type="checkpoint:human-verify" gate="blocking">
+ <name>Task 3: Verify Health tab and correlation charts</name>
+ <files>none (verification only)</files>
+ <action>
+Human verification checkpoint. Verify:
+1. Health tab appears in MeatSpace at /meatspace/health
+2. Four metric cards render correctly with empty states or data
+3. Range selector buttons work
+4. Correlation charts show threshold messages or data
+5. URL is deep-linkable
+ </action>
+ <verify>
+ <automated>curl -s http://localhost:5554/api/apple-health/range | node -e "process.stdin.on('data',d=>{console.log('PASS: range endpoint responding')})"</automated>
+ </verify>
+ <done>Health tab verified visually with cards, range selector, and correlations</done>
+ <what-built>MeatSpace Health tab with four metric cards, range selector, and two correlation charts</what-built>
+ <how-to-verify>
+ 1. Navigate to http://localhost:5555/meatspace/health
+ 2. Verify the Health tab appears in the MeatSpace tab bar (between Genome and Lifestyle)
+ 3. Verify range selector buttons (7d/30d/90d/1y) are visible and clickable
+ 4. If health data was ingested via curl in Plan 03-02 checkpoint, verify cards show data
+ 5. If no data: verify empty states display correctly ("No step data available" etc.)
+ 6. Verify card styling matches existing MeatSpace cards (dark theme, rounded corners)
+ 7. Verify correlation section shows threshold message if < 14 days of data
+ 8. Verify the URL is deep-linkable: refreshing /meatspace/health returns to the Health tab
+ </how-to-verify>
+ <resume-signal>Type "approved" or describe issues</resume-signal>
+</task>
+
+</tasks>
+
+<verification>
+1. Health tab appears in MeatSpace at /meatspace/health
+2. Four metric cards render with hero numbers and trend charts
+3. Range selector controls all cards consistently
+4. Correlation charts show dual-axis data or threshold messages
+5. All existing tests pass: `cd server && npm test`
+</verification>
+
+<success_criteria>
+- MeatSpace Health tab shows steps, heart rate, sleep, and HRV cards
+- Each card has hero number + line chart (sleep has stacked bar for stages)
+- Range selector (7d/30d/90d/1y) filters all cards
+- Alcohol vs HRV correlation shows dual-axis chart with computed text summary
+- Activity vs blood work correlation shows 30-day rolling average with markers
+- Correlations show "Need 14+ days" message when insufficient data
+- Health tab is deep-linkable at /meatspace/health
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/03-apple-health-integration/03-03-SUMMARY.md`
+</output>