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-01): complete Apple Health ingest pipeline plan

Adam Eivyc526d40c3620
diff --git a/.changelog/v1.14.x.md b/.changelog/v1.14.x.md
index bb889d86bc..7c0420bd82 100644
--- a/.changelog/v1.14.x.md
+++ b/.changelog/v1.14.x.md
@@ -8,6 +8,10 @@ Genome migration cleanup — completed the meatspace data migration so genome, C
## Features
+- **Apple Health ingest pipeline** — `POST /api/health/ingest` accepts Health Auto Export JSON, validates with Zod, deduplicates by metric+timestamp, and persists to day-partitioned files at `data/health/YYYY-MM-DD.json`
+- **Apple Health query service** — `GET /api/health/metrics/:name/daily` returns aggregated daily values, `GET /api/health/metrics/:name` returns summary stats, `GET /api/health/range` returns available data range
+- **Apple Health correlation endpoint** — `GET /api/health/correlation` merges HRV, steps, alcohol, and blood test data for cross-domain health analysis
+- **System health namespace relocation** — moved system health endpoints from `/api/health` and `/api/health/system` to `/api/system/health` and `/api/system/health/details` to free the `/api/health` namespace for Apple Health data
- **Data backup engine** — rsync-based incremental backup from `./data/` to a configured external drive path, with SHA-256 manifest generation for integrity verification after each snapshot
- **Backup REST API** — `GET /api/backup/status`, `POST /api/backup/run`, `GET /api/backup/snapshots`, `POST /api/backup/restore` with Zod request validation
- **Backup cron scheduler** — daily backup at 2 AM (configurable via `settings.backup.cronExpression`), registered with the existing eventScheduler and started at server boot
diff --git a/.planning/REQUIREMENTS.md b/.planning/REQUIREMENTS.md
index e032c84018..f9323cbae0 100644
--- a/.planning/REQUIREMENTS.md
+++ b/.planning/REQUIREMENTS.md
@@ -25,8 +25,8 @@ Requirements for this milestone batch. Each maps to roadmap phases.
### Apple Health
-- [ ] **HLT-01**: POST `/api/health/ingest` accepts Health Auto Export JSON, validates with Zod, deduplicates by metric+timestamp
-- [ ] **HLT-02**: Health data persists to day-partitioned `data/health/YYYY-MM-DD.json` files
+- [x] **HLT-01**: POST `/api/health/ingest` accepts Health Auto Export JSON, validates with Zod, deduplicates by metric+timestamp
+- [x] **HLT-02**: Health data persists to day-partitioned `data/health/YYYY-MM-DD.json` files
- [ ] **HLT-03**: Bulk XML import streams Apple Health export (500MB+) without OOM via SAX parser
- [ ] **HLT-04**: XML import reports progress via WebSocket during processing
- [ ] **HLT-05**: MeatSpace dashboard cards for steps, heart rate, sleep, HRV trends
@@ -99,8 +99,8 @@ Which phases cover which requirements. Updated during roadmap creation.
| BAK-05 | Phase 2 | Complete |
| BAK-06 | Phase 2 | Complete |
| BAK-07 | Phase 2 | Complete |
-| HLT-01 | Phase 3 | Pending |
-| HLT-02 | Phase 3 | Pending |
+| HLT-01 | Phase 3 | Complete |
+| HLT-02 | Phase 3 | Complete |
| HLT-03 | Phase 3 | Pending |
| HLT-04 | Phase 3 | Pending |
| HLT-05 | Phase 3 | Pending |
diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md
index 76d77a58bb..113772167c 100644
--- a/.planning/ROADMAP.md
+++ b/.planning/ROADMAP.md
@@ -61,7 +61,7 @@ Plans:
**Plans**: 3 plans
Plans:
-- [ ] 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)
+- [x] 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)
@@ -104,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/3 | Not started | - |
+| 3. Apple Health Integration | 1/3 | In progress | - |
| 4. Cross-Domain Insights Engine | 0/2 | Not started | - |
| 5. Unified Search (Cmd+K) | 0/1 | Not started | - |
diff --git a/.planning/STATE.md b/.planning/STATE.md
index 27190a5b5e..8240814dcc 100644
--- a/.planning/STATE.md
+++ b/.planning/STATE.md
@@ -2,13 +2,13 @@
gsd_state_version: 1.0
milestone: v1.0
milestone_name: milestone
-status: unknown
-last_updated: "2026-02-26T22:26:57.078Z"
+status: in_progress
+last_updated: "2026-02-26T23:23:20.000Z"
progress:
- total_phases: 2
+ total_phases: 5
completed_phases: 2
- total_plans: 3
- completed_plans: 3
+ total_plans: 4
+ completed_plans: 4
---
# Project State
@@ -18,16 +18,16 @@ progress:
See: .planning/PROJECT.md (updated 2026-02-26)
**Core value:** Ship five next actions that transform PortOS from siloed features into a connected, protected, and searchable system
-**Current focus:** Phase 3 - Health Auto Export (next)
+**Current focus:** Phase 3 - Health Auto Export (Plan 01 complete, Plans 02-03 remaining)
## Current Position
-Phase: 2 of 5 (Data Backup & Recovery)
-Plan: 2 of 2 in current phase (complete)
-Status: Phase complete — ready for Phase 3
-Last activity: 2026-02-26 -- Plan 02-02 complete (BackupWidget verified)
+Phase: 3 of 5 (Apple Health Integration)
+Plan: 1 of 3 in current phase (complete)
+Status: Plan 03-01 complete — ready for Plan 03-02 (XML import)
+Last activity: 2026-02-26 -- Plan 03-01 complete (Apple Health ingest pipeline + system health namespace relocation)
-Progress: [████░░░░░░] 40%
+Progress: [████░░░░░░] 44%
## Performance Metrics
@@ -42,9 +42,10 @@ Progress: [████░░░░░░] 40%
|-------|-------|-------|----------|
| 01-genome-migration-cleanup | 1 | 108s | 108s |
| 02-data-backup-recovery | 2 | 255s + ~10min | ~7min |
+| 03-apple-health-integration | 1 | 210s | 210s |
**Recent Trend:**
-- Last 5 plans: 01-01 (108s), 02-01 (135s), 02-02 (~10min)
+- Last 5 plans: 01-01 (108s), 02-01 (135s), 02-02 (~10min), 03-01 (210s)
- Trend: stable (~2-10 min/plan)
*Updated after each plan completion*
@@ -69,6 +70,10 @@ Recent decisions affecting current work:
- [Phase 02-data-backup-recovery]: Restore requires dry-run preview before enabling Restore button — prevents accidental destructive restore
- [Phase 02-data-backup-recovery plan 02]: BackupWidget placed in Dashboard Row 4 (system-status row) alongside SystemHealthWidget
- [Phase 02-data-backup-recovery plan 02]: SnapshotList fetches lazily (only when expanded) to avoid unnecessary API calls
+- [Phase 03-apple-health-integration plan 01]: extractDateStr uses substring(0,10) not Date() to avoid timezone shift on Apple Health timestamps
+- [Phase 03-apple-health-integration plan 01]: Dedup key is full date string, not extracted YYYY-MM-DD, to distinguish multiple same-day readings
+- [Phase 03-apple-health-integration plan 01]: /health/system renamed to /health/details to avoid redundancy with /api/system mount point
+- [Phase 03-apple-health-integration plan 01]: getDailyAggregates uses per-metric strategy (step_count sums, heart_rate averages Avg, sleep takes totalSleep, default averages qty)
### Pending Todos
@@ -76,12 +81,11 @@ None yet.
### Blockers/Concerns
-- Phase 3: Health Auto Export JSON schema needs validation against current app version (v7+)
-- Phase 3: Apple Health XML timezone handling (local TZ vs UTC) needs decision during planning
+- Phase 3: Apple Health XML timezone handling (local TZ vs UTC) needs decision during 03-02 planning
- Phase 4: Curating scientifically grounded correlation rules is domain work, not just engineering
## Session Continuity
Last session: 2026-02-26
-Stopped at: Completed 02-02-PLAN.md (BackupWidget — human verification approved)
+Stopped at: Completed 03-01-PLAN.md (Apple Health ingest pipeline + system health namespace relocation)
Resume file: None
diff --git a/.planning/phases/03-apple-health-integration/03-01-SUMMARY.md b/.planning/phases/03-apple-health-integration/03-01-SUMMARY.md
new file mode 100644
index 0000000000..7f73fa23ba
--- /dev/null
+++ b/.planning/phases/03-apple-health-integration/03-01-SUMMARY.md
@@ -0,0 +1,113 @@
+---
+phase: 03-apple-health-integration
+plan: "01"
+subsystem: health-ingest
+tags: [apple-health, ingest, validation, zod, day-partitioned-storage, query-service]
+dependency_graph:
+ requires: []
+ provides:
+ - POST /api/health/ingest (Health Auto Export JSON ingest with dedup)
+ - GET /api/health/metrics/:name (metric summary by date range)
+ - GET /api/health/metrics/:name/daily (daily aggregated values)
+ - GET /api/health/range (available data date range)
+ - GET /api/health/correlation (merged HRV+alcohol+steps+blood data)
+ - GET /api/system/health (renamed from /api/health)
+ - GET /api/system/health/details (renamed from /api/health/system)
+ affects:
+ - client/src/services/api.js (checkHealth, getSystemHealth paths updated; Apple Health API functions added)
+ - 03-02-PLAN.md (XML import can now call ingestHealthData)
+ - 03-03-PLAN.md (dashboard cards use getAppleHealthMetrics, getAppleHealthSummary)
+tech_stack:
+ added: []
+ patterns:
+ - Day-partitioned JSON files at data/health/YYYY-MM-DD.json
+ - Deduplication by metric name + full date string (Set-based O(1) lookup)
+ - substring(0,10) for timezone-safe date extraction from Apple Health timestamps
+ - passthrough() on Zod schemas for future Health Auto Export field compatibility
+key_files:
+ created:
+ - server/lib/appleHealthValidation.js
+ - server/services/appleHealthIngest.js
+ - server/services/appleHealthQuery.js
+ - server/routes/appleHealth.js
+ modified:
+ - server/lib/fileUtils.js (added PATHS.health)
+ - server/index.js (systemHealthRoutes at /api/system, appleHealthRoutes at /api/health)
+ - client/src/services/api.js (checkHealth/getSystemHealth paths + 5 Apple Health functions)
+ - server/routes/systemHealth.js (renamed from health.js via git mv, /health/system -> /health/details)
+ - server/routes/health.test.js (updated to import systemHealth.js, use /api/system/health)
+decisions:
+ - "Extracted YYYY-MM-DD using substring(0,10) not Date() to prevent timezone shift on Apple Health timestamps"
+ - "Used passthrough() on healthDataPointSchema and data object to support future Health Auto Export fields"
+ - "Dedup key is the full date string (not extracted date) to distinguish multiple readings on same day"
+ - "Renamed /health/system to /health/details inside systemHealth.js to avoid redundancy with /api/system mount point"
+ - "getDailyAggregates uses per-metric strategy: step_count sums qty, heart_rate averages Avg, sleep_analysis takes totalSleep, default averages qty"
+metrics:
+ duration: 210s
+ tasks_completed: 3
+ files_created: 4
+ files_modified: 5
+ completed_date: "2026-02-26"
+---
+
+# Phase 03 Plan 01: Apple Health Ingest Pipeline Summary
+
+**One-liner:** Zod-validated Health Auto Export JSON ingest with timezone-safe dedup into day-partitioned files, REST query API, correlation endpoint, and system health namespace relocation to /api/system.
+
+## What Was Built
+
+### Task 1: System Health Route Relocation
+Freed the `/api/health` namespace by moving system health endpoints:
+- `server/routes/health.js` renamed to `server/routes/systemHealth.js` via `git mv`
+- Route `/health/system` renamed to `/health/details` inside the file (avoids redundancy with mount at `/api/system`)
+- `server/index.js`: `app.use('/api/system', systemHealthRoutes)` replaces `app.use('/api', healthRoutes)`
+- `client/src/services/api.js`: `checkHealth` now calls `/system/health`, `getSystemHealth` calls `/system/health/details`
+- Test updated to import `systemHealth.js` and use new path
+
+### Task 2: Validation Schemas and Ingest Service
+- `server/lib/appleHealthValidation.js`: `healthDataPointSchema` (passthrough for future fields), `healthMetricSchema`, `healthIngestSchema`
+- `server/lib/fileUtils.js`: added `PATHS.health = data/health/`
+- `server/services/appleHealthIngest.js`:
+ - `extractDateStr()`: uses `substring(0,10)` to avoid timezone conversion (research pitfall 5)
+ - `dedupKey()`: produces `metricName::dateString` composite key
+ - `readDayFile()` / `writeDayFile()`: reads/writes `data/health/YYYY-MM-DD.json`
+ - `mergeIntoDay()`: deduplicates by building Set of existing date strings, appends only unique points
+ - `ingestHealthData()`: groups all metric data points by day, calls mergeIntoDay, returns `{ metricsProcessed, recordsIngested, recordsSkipped, daysAffected }`
+
+### Task 3: Query Service, REST Routes, and Client Functions
+- `server/services/appleHealthQuery.js`:
+ - `listDayFiles()`: reads health dir, filters/sorts YYYY-MM-DD.json files
+ - `getAvailableDateRange()`: returns `{ from, to, totalDays }` or null
+ - `getMetrics()`: flat array of all data points for a metric in date range
+ - `getMetricSummary()`: count, latest, average (qty or Avg), plus raw dataPoints
+ - `getDailyAggregates()`: per-metric strategy (step_count sums, heart_rate averages Avg, HRV averages qty, sleep takes totalSleep, others average qty)
+ - `getCorrelationData()`: merges HRV + steps + alcohol (from meatspaceAlcohol) + blood tests (from meatspaceHealth)
+- `server/routes/appleHealth.js`: 5 REST endpoints using asyncHandler + validateRequest pattern
+- `server/index.js`: registered `app.use('/api/health', appleHealthRoutes)` before `/api/instances`
+- `client/src/services/api.js`: added `ingestAppleHealth`, `getAppleHealthMetrics`, `getAppleHealthSummary`, `getAppleHealthRange`, `getAppleHealthCorrelation`
+
+## Decisions Made
+
+1. **Timezone-safe date extraction** — `substring(0,10)` instead of `new Date()` to avoid timezone shift on Apple Health timestamps like `"2024-01-15 08:30:00 -0800"`. `new Date()` would convert to UTC, shifting dates near midnight to the wrong day.
+
+2. **passthrough() on schemas** — `healthDataPointSchema` and the `data` object use `.passthrough()` so future fields added by Health Auto Export app updates don't break validation.
+
+3. **Full date string as dedup key** — Dedup uses the full date string from the data point (e.g., `"2024-01-15 08:30:00 -0800"`), not just the extracted YYYY-MM-DD. This correctly distinguishes multiple readings on the same calendar day (e.g., two heart rate readings at different times).
+
+4. **Route rename from /health/system to /health/details** — When mounting at `/api/system`, the route `/health/system` would produce `/api/system/health/system` which is redundant. Renamed to `/health/details` for `/api/system/health/details`.
+
+5. **Per-metric daily aggregation strategies** — Different metrics require different aggregation: step_count needs a sum (not average) of all steps in a day; heart_rate uses the `Avg` field not `qty`; sleep_analysis has `totalSleep` not `qty`. Hardcoded per-metric strategies with a sensible default.
+
+## Deviations from Plan
+
+None — plan executed exactly as written.
+
+## Self-Check: PASSED
+
+Verified:
+- `server/lib/appleHealthValidation.js` exists and healthIngestSchema validates test payload
+- `server/services/appleHealthIngest.js` loads, extractDateStr returns `2024-01-15` from `"2024-01-15 08:30:00 -0800"`
+- `server/services/appleHealthQuery.js` loads, getMetrics and getDailyAggregates are functions
+- `server/routes/appleHealth.js` loads, router exported
+- All 1192 tests pass (42 test files, 0 regressions)
+- Commits: 7c2a592 (Task 1), 200a0d2 (Task 2), 2cd855f (Task 3)