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-02): add SAX streaming XML import service and POST /import/xml route

Adam Eivy89674159ae30
diff --git a/server/package-lock.json b/server/package-lock.json
index ce68ce54fc..6d86c6325e 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -11,9 +11,11 @@
"axios": "^1.7.9",
"cors": "^2.8.5",
"express": "^4.21.2",
+ "multer": "^2.0.2",
"node-pty": "^1.2.0-beta.10",
"pm2": "^5.4.3",
"portos-ai-toolkit": "^0.5.0",
+ "sax": "^1.4.4",
"socket.io": "^4.8.3",
"socket.io-client": "^4.8.3",
"uuid": "^11.0.3",
@@ -1497,6 +1499,12 @@
"node": ">= 8"
}
},
+ "node_modules/append-field": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
+ "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
+ "license": "MIT"
+ },
"node_modules/argparse": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
@@ -1669,6 +1677,17 @@
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
+ "node_modules/busboy": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
+ "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
+ "dependencies": {
+ "streamsearch": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=10.16.0"
+ }
+ },
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -1817,6 +1836,21 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/concat-stream": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
+ "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
+ "engines": [
+ "node >= 6.0"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "buffer-from": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.0.2",
+ "typedarray": "^0.0.6"
+ }
+ },
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
@@ -3136,6 +3170,15 @@
"node": ">= 0.6"
}
},
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/mkdirp": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
@@ -3160,6 +3203,36 @@
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
+ "node_modules/multer": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.2.tgz",
+ "integrity": "sha512-u7f2xaZ/UG8oLXHvtF/oWTRvT44p9ecwBBqTwgJVq0+4BW1g8OW01TyMEGWBHbyMOYVHXslaut7qEQ1meATXgw==",
+ "license": "MIT",
+ "dependencies": {
+ "append-field": "^1.0.0",
+ "busboy": "^1.6.0",
+ "concat-stream": "^2.0.0",
+ "mkdirp": "^0.5.6",
+ "object-assign": "^4.1.1",
+ "type-is": "^1.6.18",
+ "xtend": "^4.0.2"
+ },
+ "engines": {
+ "node": ">= 10.16.0"
+ }
+ },
+ "node_modules/multer/node_modules/mkdirp": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
+ "license": "MIT",
+ "dependencies": {
+ "minimist": "^1.2.6"
+ },
+ "bin": {
+ "mkdirp": "bin/cmd.js"
+ }
+ },
"node_modules/mute-stream": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz",
@@ -3856,6 +3929,20 @@
"node": ">=0.8"
}
},
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -4017,10 +4104,13 @@
"license": "MIT"
},
"node_modules/sax": {
- "version": "1.4.3",
- "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.3.tgz",
- "integrity": "sha512-yqYn1JhPczigF94DMS+shiDMjDowYO6y9+wB/4WgO0Y19jWYk0lQ4tuG5KI7kj4FTp1wxPj5IFfcrz/s1c3jjQ==",
- "license": "BlueOak-1.0.0"
+ "version": "1.4.4",
+ "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.4.tgz",
+ "integrity": "sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==",
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=11.0.0"
+ }
},
"node_modules/semver": {
"version": "7.7.3",
@@ -4466,6 +4556,23 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/streamsearch": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
+ "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
"node_modules/superagent": {
"version": "10.3.0",
"resolved": "https://registry.npmjs.org/superagent/-/superagent-10.3.0.tgz",
@@ -4745,6 +4852,12 @@
"node": ">= 0.6"
}
},
+ "node_modules/typedarray": {
+ "version": "0.0.6",
+ "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
+ "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
+ "license": "MIT"
+ },
"node_modules/undici-types": {
"version": "7.16.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
@@ -4760,6 +4873,12 @@
"node": ">= 0.8"
}
},
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "license": "MIT"
+ },
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -5068,6 +5187,15 @@
"node": ">=0.4.0"
}
},
+ "node_modules/xtend": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4"
+ }
+ },
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
diff --git a/server/package.json b/server/package.json
index 027fa1e5f0..0c01d41970 100644
--- a/server/package.json
+++ b/server/package.json
@@ -14,9 +14,11 @@
"axios": "^1.7.9",
"cors": "^2.8.5",
"express": "^4.21.2",
+ "multer": "^2.0.2",
"node-pty": "^1.2.0-beta.10",
"pm2": "^5.4.3",
"portos-ai-toolkit": "^0.5.0",
+ "sax": "^1.4.4",
"socket.io": "^4.8.3",
"socket.io-client": "^4.8.3",
"uuid": "^11.0.3",
diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.js
index 180c6e5941..30cb07ecba 100644
--- a/server/routes/appleHealth.js
+++ b/server/routes/appleHealth.js
@@ -1,8 +1,11 @@
import { Router } from 'express';
-import { asyncHandler } from '../lib/errorHandler.js';
+import { tmpdir } from 'os';
+import multer from 'multer';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { healthIngestSchema } from '../lib/appleHealthValidation.js';
import { ingestHealthData } from '../services/appleHealthIngest.js';
+import { importAppleHealthXml } from '../services/appleHealthXml.js';
import {
getMetricSummary,
getDailyAggregates,
@@ -10,6 +13,21 @@ import {
getCorrelationData
} from '../services/appleHealthQuery.js';
+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', { status: 400, code: 'BAD_REQUEST' }));
+ }
+ }
+});
+
const router = Router();
// POST /api/health/ingest
@@ -53,4 +71,14 @@ router.get('/correlation', asyncHandler(async (req, res) => {
res.json(data);
}));
+// POST /api/health/import/xml
+// Accepts Apple Health export.xml via multipart upload (multer diskStorage — no OOM on 500MB+)
+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', { status: 400, code: 'BAD_REQUEST' });
+ const result = await importAppleHealthXml(filePath, io);
+ res.json(result);
+}));
+
export default router;
diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.js
new file mode 100644
index 0000000000..bc34204a95
--- /dev/null
+++ b/server/services/appleHealthXml.js
@@ -0,0 +1,230 @@
+/**
+ * Apple Health XML Import Service
+ *
+ * SAX streaming parser for Apple Health exports (500MB+).
+ * Normalizes HK identifiers to metric names matching JSON ingest format.
+ * Emits WebSocket progress events every 10k records.
+ */
+
+import sax from 'sax';
+import { createReadStream } from 'fs';
+import { unlink } from 'fs';
+import { extractDateStr, readDayFile, writeDayFile } from './appleHealthIngest.js';
+
+// === Mapping Tables ===
+
+const XML_TO_METRIC_NAME = {
+ 'hkquantitytypeidentifierstepcount': 'step_count',
+ 'hkquantitytypeidentifierheartrate': 'heart_rate',
+ 'hkquantitytypeidentifierheartratevariancessdnn': 'heart_rate_variability_sdnn',
+ 'hkquantitytypeidentifierheartratevariancessdnn': 'heart_rate_variability_sdnn',
+ 'hkcategorytypeidentifiersleepanalysis': 'sleep_analysis',
+};
+
+// HKQuantityTypeIdentifierHeartRateVariabilitySDNN mapped by direct lowercase below
+// Using the exact HK identifier (already lowercase) as fallback for unknowns
+
+const SLEEP_STAGE_MAP = {
+ 'hkcategoryvaluesleepanalysisasleepdeep': 'deep',
+ 'hkcategoryvaluesleepanalysisasleeprem': 'rem',
+ 'hkcategoryvaluesleepanalysisasleepcore': 'core',
+ 'hkcategoryvaluesleepanalysisawake': 'awake',
+ 'hkcategoryvaluesleepanalysisinbed': 'inBed',
+ 'hkcategoryvaluesleepanalysisasleep': 'asleep', // Legacy pre-iOS 16
+};
+
+// === Pure Functions ===
+
+/**
+ * Normalize an XML Record node into a standard data point.
+ * Uses lowercase attribute names (sax non-strict lowercase mode).
+ *
+ * @param {Object} node - SAX opentag node with lowercase attributes
+ * @returns {{ metricName: string, dateStr: string, dataPoint: Object }|null}
+ */
+export function normalizeXmlRecord(node) {
+ const attrs = node.attributes;
+ const type = attrs.type;
+ const value = attrs.value;
+ const startdate = attrs.startdate;
+ const enddate = attrs.enddate;
+ const unit = attrs.unit;
+ const sourcename = attrs.sourcename;
+
+ if (!type || !startdate) return null;
+
+ const typeLower = type.toLowerCase();
+ const metricName = XML_TO_METRIC_NAME[typeLower] ?? typeLower;
+
+ const dateStr = extractDateStr(startdate);
+ if (!dateStr) return null;
+
+ // Sleep analysis: categorical value → duration-based stage data
+ if (typeLower === 'hkcategorytypeidentifiersleepanalysis') {
+ const durationHours = enddate
+ ? (new Date(enddate) - new Date(startdate)) / 3600000
+ : 0;
+ const valueLower = value?.toLowerCase() ?? '';
+ const stage = SLEEP_STAGE_MAP[valueLower] ?? value ?? 'unknown';
+ const dataPoint = { date: startdate, stage, durationHours };
+ return { metricName, dateStr, dataPoint };
+ }
+
+ // Heart rate: include end timestamp
+ if (typeLower === 'hkquantitytypeidentifierheartrate') {
+ const dataPoint = {
+ date: startdate,
+ qty: parseFloat(value),
+ unit: unit ?? null,
+ src: sourcename ?? null,
+ end: enddate ?? null,
+ };
+ return { metricName, dateStr, dataPoint };
+ }
+
+ // All other numeric types
+ const dataPoint = {
+ date: startdate,
+ qty: parseFloat(value),
+ unit: unit ?? null,
+ src: sourcename ?? null,
+ };
+ return { metricName, dateStr, dataPoint };
+}
+
+// === Aggregation ===
+
+/**
+ * Aggregate step_count entries in a day bucket — sum all qty values into a single total.
+ * Apple Health emits per-activity step records; we want the daily total.
+ *
+ * @param {Array} points - Array of step_count data points
+ * @returns {Array} Single-element array with aggregated total
+ */
+function aggregateStepCount(points) {
+ if (!points.length) return points;
+ const total = points.reduce((sum, p) => sum + (p.qty || 0), 0);
+ // Use first point's date for the aggregated entry
+ return [{ date: points[0].date, qty: total, unit: points[0].unit ?? null }];
+}
+
+/**
+ * Aggregate sleep_analysis entries in a day bucket — sum duration by stage per day.
+ *
+ * @param {Array} points - Array of sleep_analysis data points with stage/durationHours
+ * @returns {Object} Aggregated sleep summary { date, totalSleep, deep, rem, core, awake, inBed, asleep }
+ */
+function aggregateSleepAnalysis(points) {
+ if (!points.length) return points;
+ const summary = { date: points[0].date, totalSleep: 0, deep: 0, rem: 0, core: 0, awake: 0, inBed: 0, asleep: 0 };
+ for (const p of points) {
+ const stage = p.stage;
+ const dur = p.durationHours || 0;
+ if (stage === 'deep') summary.deep += dur;
+ else if (stage === 'rem') summary.rem += dur;
+ else if (stage === 'core') summary.core += dur;
+ else if (stage === 'awake') summary.awake += dur;
+ else if (stage === 'inBed') summary.inBed += dur;
+ else if (stage === 'asleep') summary.asleep += dur;
+ }
+ // totalSleep = meaningful sleep stages (deep + rem + core)
+ summary.totalSleep = summary.deep + summary.rem + summary.core;
+ return [summary];
+}
+
+// === Main Export ===
+
+/**
+ * Stream-parse an Apple Health export.xml file using SAX.
+ * Accumulates records, aggregates step/sleep metrics, then writes day files.
+ *
+ * @param {string} filePath - Absolute path to the XML file (temp upload)
+ * @param {Object|null} io - Socket.IO server instance for progress events
+ * @returns {Promise<{ days: number, records: number }>}
+ */
+export async function importAppleHealthXml(filePath, io = null) {
+ // dayBuckets: { [dateStr]: { [metricName]: [...dataPoints] } }
+ const dayBuckets = {};
+ let processedRecords = 0;
+
+ await new Promise((resolve, reject) => {
+ const saxStream = sax.createStream(false, { lowercase: true });
+
+ saxStream.on('opentag', (node) => {
+ if (node.name !== 'record') return;
+
+ const normalized = normalizeXmlRecord(node);
+ if (!normalized) return;
+
+ const { metricName, dateStr, dataPoint } = normalized;
+
+ if (!dayBuckets[dateStr]) dayBuckets[dateStr] = {};
+ if (!dayBuckets[dateStr][metricName]) dayBuckets[dateStr][metricName] = [];
+ dayBuckets[dateStr][metricName].push(dataPoint);
+
+ processedRecords++;
+
+ if (processedRecords % 10000 === 0) {
+ io?.emit('health:xml:progress', { processed: processedRecords });
+ console.log(`🍎 XML import progress: ${processedRecords} records`);
+ }
+ });
+
+ saxStream.on('error', function (e) {
+ console.error(`❌ XML parse error at record ${processedRecords}: ${e.message}`);
+ // Clear error and resume — Apple Health XML can have minor malformations
+ this._parser.error = null;
+ this._parser.resume();
+ });
+
+ saxStream.on('end', resolve);
+ saxStream.on('close', resolve);
+
+ createReadStream(filePath).pipe(saxStream);
+ });
+
+ console.log(`🍎 XML parsing done: ${processedRecords} raw records across ${Object.keys(dayBuckets).length} days — starting aggregation`);
+
+ // === Post-parse aggregation (outside SAX event loop) ===
+ for (const dateStr of Object.keys(dayBuckets)) {
+ const metrics = dayBuckets[dateStr];
+
+ // Aggregate step_count: sum all qty values into single daily total
+ if (metrics.step_count) {
+ metrics.step_count = aggregateStepCount(metrics.step_count);
+ }
+
+ // Aggregate sleep_analysis: sum stage durations into daily summary
+ if (metrics.sleep_analysis) {
+ metrics.sleep_analysis = aggregateSleepAnalysis(metrics.sleep_analysis);
+ }
+ }
+
+ // === Write day files sequentially ===
+ const allDates = Object.keys(dayBuckets);
+ for (const dateStr of allDates) {
+ const dayData = await readDayFile(dateStr);
+ const metrics = dayBuckets[dateStr];
+
+ for (const [metricName, newPoints] of Object.entries(metrics)) {
+ const existing = dayData.metrics[metricName] || [];
+ const existingDates = new Set(existing.map(p => p.date));
+ const uniquePoints = newPoints.filter(p => !existingDates.has(p.date));
+ if (uniquePoints.length > 0) {
+ dayData.metrics[metricName] = existing.concat(uniquePoints);
+ }
+ }
+
+ await writeDayFile(dateStr, dayData);
+ }
+
+ const daysCount = allDates.length;
+
+ // Clean up temp file
+ unlink(filePath, () => {});
+
+ io?.emit('health:xml:complete', { days: daysCount, records: processedRecords });
+ console.log(`🍎 XML import complete: ${processedRecords} records across ${daysCount} days`);
+
+ return { days: daysCount, records: processedRecords };
+}