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(03-01): create Apple Health validation schemas and ingest service
Adam Eivy200a0d2591e4
diff --git a/server/lib/appleHealthValidation.js b/server/lib/appleHealthValidation.jsnew file mode 100644index 0000000000..81c6d4165b--- /dev/null+++ b/server/lib/appleHealthValidation.js@@ -0,0 +1,51 @@+import { z } from 'zod';++// =============================================================================+// APPLE HEALTH INGEST SCHEMAS+// Validates payloads from the Health Auto Export iOS app (v7+)+// =============================================================================++/**+ * Individual data point from a health metric.+ * Uses passthrough to allow future fields added by app updates.+ */+export const healthDataPointSchema = z.object({+ date: z.string().min(1),+ qty: z.number().optional(),+ // Heart rate fields+ Min: z.number().optional(),+ Avg: z.number().optional(),+ Max: z.number().optional(),+ // Sleep analysis fields+ totalSleep: z.number().optional(),+ deep: z.number().optional(),+ rem: z.number().optional(),+ core: z.number().optional(),+ awake: z.number().optional()+}).passthrough();++/**+ * A named health metric with its associated data points.+ */+export const healthMetricSchema = z.object({+ name: z.string().min(1),+ units: z.string().optional(),+ data: z.array(healthDataPointSchema)+});++/**+ * Top-level ingest payload schema matching Health Auto Export JSON format:+ * {+ * "data": {+ * "metrics": [...],+ * "workouts": [...]+ * }+ * }+ * Uses passthrough on the data object to allow future Health Auto Export fields.+ */+export const healthIngestSchema = z.object({+ data: z.object({+ metrics: z.array(healthMetricSchema).default([]),+ workouts: z.array(z.unknown()).default([])+ }).passthrough()+});diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex a900db186a..312a3416ef 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -21,6 +21,7 @@ export const PATHS = {cos: join(__lib_dirname, '../../data/cos'),brain: join(__lib_dirname, '../../data/brain'),digitalTwin: join(__lib_dirname, '../../data/digital-twin'),+ health: join(__lib_dirname, '../../data/health'),runs: join(__lib_dirname, '../../data/runs'),memory: join(__lib_dirname, '../../data/cos/memory'),cosAgents: join(__lib_dirname, '../../data/cos/agents'), // CoS sub-agentsdiff --git a/server/services/appleHealthIngest.js b/server/services/appleHealthIngest.jsnew file mode 100644index 0000000000..588d268705--- /dev/null+++ b/server/services/appleHealthIngest.js@@ -0,0 +1,139 @@+/**+ * Apple Health Ingest Service+ *+ * Handles JSON ingest from Health Auto Export app, deduplication by+ * metric+timestamp, and day-partitioned file storage at data/health/YYYY-MM-DD.json.+ */++import { writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++// === Pure Functions ===++/**+ * Extract YYYY-MM-DD from an Apple Health timestamp string.+ * Uses substring (not Date parsing) to avoid timezone conversion issues.+ * Apple Health timestamps are like: "2024-01-15 08:30:00 -0800"+ *+ * @param {string} dateString - Apple Health timestamp string+ * @returns {string|null} YYYY-MM-DD string or null if invalid+ */+export function extractDateStr(dateString) {+ if (!dateString || typeof dateString !== 'string') return null;+ const candidate = dateString.substring(0, 10);+ if (!/^\d{4}-\d{2}-\d{2}$/.test(candidate)) return null;+ return candidate;+}++/**+ * Generate a deduplication key from metric name and data point date string.+ *+ * @param {string} metricName - The health metric name (e.g. "step_count")+ * @param {string} dateString - The full date string from the data point+ * @returns {string} Dedup key+ */+export function dedupKey(metricName, dateString) {+ return `${metricName}::${dateString}`;+}++// === File I/O ===++/**+ * Read a day file for a given date string.+ *+ * @param {string} dateStr - YYYY-MM-DD string+ * @returns {Promise<Object>} Day file data with date and metrics map+ */+export async function readDayFile(dateStr) {+ const filePath = join(PATHS.health, `${dateStr}.json`);+ return readJSONFile(filePath, { date: dateStr, metrics: {} });+}++/**+ * Write a day file, setting the updated timestamp.+ *+ * @param {string} dateStr - YYYY-MM-DD string+ * @param {Object} data - Day file data to write+ * @returns {Promise<void>}+ */+export async function writeDayFile(dateStr, data) {+ await ensureDir(PATHS.health);+ data.updated = new Date().toISOString();+ const filePath = join(PATHS.health, `${dateStr}.json`);+ await writeFile(filePath, JSON.stringify(data, null, 2));+}++/**+ * Merge new data points into an existing day file, deduplicating by date string.+ *+ * @param {string} dateStr - YYYY-MM-DD string+ * @param {string} metricName - Health metric name+ * @param {Array} newPoints - Array of data point objects from the metric+ * @returns {Promise<number>} Count of newly added (unique) points+ */+export async function mergeIntoDay(dateStr, metricName, newPoints) {+ const dayData = await readDayFile(dateStr);++ const existing = dayData.metrics[metricName] || [];++ // Build a Set of existing full date strings for fast dedup lookup+ const existingDates = new Set(existing.map(p => p.date));++ // Only keep points not already present+ const uniquePoints = newPoints.filter(p => !existingDates.has(p.date));++ if (uniquePoints.length > 0) {+ dayData.metrics[metricName] = existing.concat(uniquePoints);+ await writeDayFile(dateStr, dayData);+ }++ return uniquePoints.length;+}++// === Main Ingest Entry Point ===++/**+ * Ingest a validated Health Auto Export payload.+ * Iterates all metrics, groups data points by day, and merges into day files.+ *+ * @param {Object} payload - Validated health ingest payload+ * @returns {Promise<Object>} Summary: { metricsProcessed, recordsIngested, recordsSkipped, daysAffected }+ */+export async function ingestHealthData(payload) {+ const metrics = payload.data.metrics || [];+ let metricsProcessed = 0;+ let recordsIngested = 0;+ let recordsSkipped = 0;+ const affectedDays = new Set();++ for (const metric of metrics) {+ const { name: metricName, data: dataPoints = [] } = metric;+ metricsProcessed++;++ // Group data points by extracted day string+ const byDay = new Map();+ for (const point of dataPoints) {+ const dateStr = extractDateStr(point.date);+ if (!dateStr) {+ recordsSkipped++;+ continue;+ }+ if (!byDay.has(dateStr)) byDay.set(dateStr, []);+ byDay.get(dateStr).push(point);+ }++ // Merge each day's points into the corresponding day file+ for (const [dateStr, points] of byDay) {+ const added = await mergeIntoDay(dateStr, metricName, points);+ recordsIngested += added;+ recordsSkipped += (points.length - added);+ if (added > 0) affectedDays.add(dateStr);+ }+ }++ const daysAffected = affectedDays.size;+ console.log(`🍎 Health ingest: ${recordsIngested} records across ${daysAffected} days (${recordsSkipped} dupes skipped)`);++ return { metricsProcessed, recordsIngested, recordsSkipped, daysAffected };+}