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 query service, REST routes, and client API functions
Adam Eivy2cd855f04658
diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 24aedbfe0b..a47ceb3cf1 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -40,6 +40,31 @@ async function request(endpoint, options = {}) {return response.json();}+// Apple Health+export const ingestAppleHealth = (data) => request('/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(`/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(`/health/metrics/${metricName}?${params}`);+};+export const getAppleHealthRange = () => request('/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(`/health/correlation?${params}`);+};+// Healthexport const checkHealth = () => request('/system/health');export const getSystemHealth = (options) => request('/system/health/details', options);diff --git a/server/index.js b/server/index.jsindex 55ff680c7f..7463c485a4 100644--- a/server/index.js+++ b/server/index.js@@ -5,6 +5,7 @@ import { Server } from 'socket.io';import { fileURLToPath } from 'url';import { dirname, join } from 'path';+import appleHealthRoutes from './routes/appleHealth.js';import systemHealthRoutes from './routes/systemHealth.js';import appsRoutes from './routes/apps.js';import portsRoutes from './routes/ports.js';@@ -216,6 +217,7 @@ app.use('/api/digital-twin', digitalTwinRoutes);app.use('/api/lmstudio', lmstudioRoutes);app.use('/api/browser', browserRoutes);app.use('/api/jira', jiraRoutes);+app.use('/api/health', appleHealthRoutes);app.use('/api/instances', instancesRoutes);app.use('/api/meatspace', meatspaceRoutes);app.use('/api/settings', settingsRoutes);diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.jsnew file mode 100644index 0000000000..180c6e5941--- /dev/null+++ b/server/routes/appleHealth.js@@ -0,0 +1,56 @@+import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { healthIngestSchema } from '../lib/appleHealthValidation.js';+import { ingestHealthData } from '../services/appleHealthIngest.js';+import {+ getMetricSummary,+ getDailyAggregates,+ getAvailableDateRange,+ getCorrelationData+} from '../services/appleHealthQuery.js';++const router = Router();++// POST /api/health/ingest+// Accepts Health Auto Export JSON, validates, deduplicates, and persists+router.post('/ingest', asyncHandler(async (req, res) => {+ const validated = validateRequest(healthIngestSchema, req.body);+ const result = await ingestHealthData(validated);+ res.json(result);+}));++// GET /api/health/metrics/:metricName+// Returns summary stats for a metric over a date range+router.get('/metrics/:metricName', asyncHandler(async (req, res) => {+ const { metricName } = req.params;+ const { from, to } = req.query;+ const summary = await getMetricSummary(metricName, from, to);+ res.json(summary);+}));++// GET /api/health/metrics/:metricName/daily+// Returns daily aggregated values for a metric over a date range+router.get('/metrics/:metricName/daily', asyncHandler(async (req, res) => {+ const { metricName } = req.params;+ const { from, to } = req.query;+ const daily = await getDailyAggregates(metricName, from, to);+ res.json(daily);+}));++// GET /api/health/range+// Returns available date range from all health day files+router.get('/range', asyncHandler(async (req, res) => {+ const range = await getAvailableDateRange();+ res.json(range);+}));++// GET /api/health/correlation+// Returns merged HRV + alcohol + steps + blood data for correlation analysis+router.get('/correlation', asyncHandler(async (req, res) => {+ const { from, to } = req.query;+ const data = await getCorrelationData(from, to);+ res.json(data);+}));++export default router;diff --git a/server/services/appleHealthQuery.js b/server/services/appleHealthQuery.jsnew file mode 100644index 0000000000..6655063b6d--- /dev/null+++ b/server/services/appleHealthQuery.js@@ -0,0 +1,220 @@+/**+ * Apple Health Query Service+ *+ * Date-range queries for health metrics stored as day-partitioned files+ * at data/health/YYYY-MM-DD.json.+ */++import { readdir } from 'fs/promises';+import { PATHS } from '../lib/fileUtils.js';+import { readDayFile } from './appleHealthIngest.js';+import { getDailyAlcohol } from './meatspaceAlcohol.js';+import { getBloodTests } from './meatspaceHealth.js';++// === Directory Listing ===++/**+ * List all available day files in the health data directory.+ *+ * @returns {Promise<string[]>} Sorted array of date strings (YYYY-MM-DD)+ */+export async function listDayFiles() {+ const files = await readdir(PATHS.health).catch(() => []);+ return files+ .filter(f => /^\d{4}-\d{2}-\d{2}\.json$/.test(f))+ .map(f => f.replace('.json', ''))+ .sort();+}++/**+ * Get the available date range from all health day files.+ *+ * @returns {Promise<Object|null>} { from, to, totalDays } or null if no files+ */+export async function getAvailableDateRange() {+ const dates = await listDayFiles();+ if (dates.length === 0) return null;+ return { from: dates[0], to: dates[dates.length - 1], totalDays: dates.length };+}++// === Metric Queries ===++/**+ * Compute default date range: last 7 days from today.+ *+ * @returns {{ from: string, to: string }}+ */+function defaultDateRange() {+ const to = new Date().toISOString().substring(0, 10);+ const fromDate = new Date();+ fromDate.setDate(fromDate.getDate() - 7);+ const from = fromDate.toISOString().substring(0, 10);+ return { from, to };+}++/**+ * Get all data points for a metric across a date range.+ * Returns flat array sorted by date.+ *+ * @param {string} metricName - Health metric name+ * @param {string} [from] - Start date YYYY-MM-DD (defaults to 7 days ago)+ * @param {string} [to] - End date YYYY-MM-DD (defaults to today)+ * @returns {Promise<Array>} Flat sorted array of data points+ */+export async function getMetrics(metricName, from, to) {+ const dates = await listDayFiles();+ const range = from && to ? { from, to } : defaultDateRange();++ const filtered = dates.filter(d => d >= range.from && d <= range.to);+ const allPoints = [];++ for (const dateStr of filtered) {+ const dayData = await readDayFile(dateStr);+ const points = dayData.metrics?.[metricName] || [];+ allPoints.push(...points);+ }++ return allPoints.sort((a, b) => a.date.localeCompare(b.date));+}++/**+ * Get summary statistics for a metric over a date range.+ *+ * @param {string} metricName - Health metric name+ * @param {string} [from] - Start date YYYY-MM-DD+ * @param {string} [to] - End date YYYY-MM-DD+ * @returns {Promise<Object>} Summary: { metricName, count, latest, average, from, to, dataPoints }+ */+export async function getMetricSummary(metricName, from, to) {+ const range = from && to ? { from, to } : defaultDateRange();+ const dataPoints = await getMetrics(metricName, range.from, range.to);++ const count = dataPoints.length;+ const latest = count > 0 ? dataPoints[dataPoints.length - 1] : null;++ // Average: use qty if present, fall back to Avg (heart rate)+ let average = null;+ if (count > 0) {+ const hasQty = dataPoints.some(p => p.qty !== undefined);+ const hasAvg = dataPoints.some(p => p.Avg !== undefined);+ if (hasQty) {+ const qtyPoints = dataPoints.filter(p => p.qty !== undefined);+ average = qtyPoints.reduce((sum, p) => sum + p.qty, 0) / qtyPoints.length;+ } else if (hasAvg) {+ const avgPoints = dataPoints.filter(p => p.Avg !== undefined);+ average = avgPoints.reduce((sum, p) => sum + p.Avg, 0) / avgPoints.length;+ }+ if (average !== null) average = Math.round(average * 100) / 100;+ }++ return { metricName, count, latest, average, from: range.from, to: range.to, dataPoints };+}++/**+ * Get daily aggregated values for a metric over a date range.+ * Aggregation strategy depends on metric type.+ *+ * @param {string} metricName - Health metric name+ * @param {string} [from] - Start date YYYY-MM-DD+ * @param {string} [to] - End date YYYY-MM-DD+ * @returns {Promise<Array>} Array of { date, value } objects+ */+export async function getDailyAggregates(metricName, from, to) {+ const dates = await listDayFiles();+ const range = from && to ? { from, to } : defaultDateRange();+ const filtered = dates.filter(d => d >= range.from && d <= range.to);+ const results = [];++ for (const dateStr of filtered) {+ const dayData = await readDayFile(dateStr);+ const points = dayData.metrics?.[metricName] || [];+ if (points.length === 0) continue;++ let value;+ if (metricName === 'step_count') {+ // Sum qty per day+ value = points.reduce((sum, p) => sum + (p.qty ?? 0), 0);+ } else if (metricName === 'heart_rate') {+ // Average of Avg values+ const avgPoints = points.filter(p => p.Avg !== undefined);+ value = avgPoints.length > 0+ ? avgPoints.reduce((sum, p) => sum + p.Avg, 0) / avgPoints.length+ : null;+ } else if (metricName === 'heart_rate_variability_sdnn') {+ // Average qty per day+ const qtyPoints = points.filter(p => p.qty !== undefined);+ value = qtyPoints.length > 0+ ? qtyPoints.reduce((sum, p) => sum + p.qty, 0) / qtyPoints.length+ : null;+ } else if (metricName === 'sleep_analysis') {+ // Take totalSleep directly from the most recent point+ const sleepPoint = points.find(p => p.totalSleep !== undefined);+ value = sleepPoint?.totalSleep ?? null;+ } else {+ // Default: average qty+ const qtyPoints = points.filter(p => p.qty !== undefined);+ value = qtyPoints.length > 0+ ? qtyPoints.reduce((sum, p) => sum + p.qty, 0) / qtyPoints.length+ : null;+ }++ if (value !== null) {+ results.push({ date: dateStr, value: Math.round(value * 100) / 100 });+ }+ }++ return results;+}++// === Correlation Data ===++/**+ * Get merged health + alcohol + blood data for correlation analysis.+ * Reads HRV, steps, and alcohol data by day, plus blood tests for date range.+ *+ * @param {string} [from] - Start date YYYY-MM-DD+ * @param {string} [to] - End date YYYY-MM-DD+ * @returns {Promise<Object>} { dailyData: Array<{ date, hrv, alcoholGrams, steps }>, bloodTests }+ */+export async function getCorrelationData(from, to) {+ const range = from && to ? { from, to } : defaultDateRange();++ const [hrvData, stepsData, alcoholEntries, bloodData] = await Promise.all([+ getDailyAggregates('heart_rate_variability_sdnn', range.from, range.to),+ getDailyAggregates('step_count', range.from, range.to),+ getDailyAlcohol(range.from, range.to),+ getBloodTests()+ ]);++ // Build lookup maps for O(1) access+ const hrvByDate = new Map(hrvData.map(d => [d.date, d.value]));+ const stepsByDate = new Map(stepsData.map(d => [d.date, d.value]));+ const alcoholByDate = new Map(+ alcoholEntries.map(e => [e.date, e.alcohol?.standardDrinks ?? 0])+ );++ // Collect all unique dates across all sources+ const allDates = new Set([+ ...hrvByDate.keys(),+ ...stepsByDate.keys(),+ ...alcoholByDate.keys()+ ]);++ const dailyData = Array.from(allDates)+ .sort()+ .map(date => ({+ date,+ hrv: hrvByDate.get(date) ?? null,+ alcoholGrams: alcoholByDate.get(date)+ ? Math.round(alcoholByDate.get(date) * 14 * 100) / 100 // std drinks to grams+ : null,+ steps: stepsByDate.get(date) ?? null+ }));++ // Filter blood tests to date range+ const bloodTests = (bloodData.tests || []).filter(+ t => t.date >= range.from && t.date <= range.to+ );++ return { dailyData, bloodTests };+}