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: import Apple Health clinical records (FHIR lab results) and show latest metric values

Adam Eivy833bac6c8a0c
diff --git a/.changelog/v1.15.x.md b/.changelog/v1.15.x.md
index 452872b42c..fd94cb2450 100644
--- a/.changelog/v1.15.x.md
+++ b/.changelog/v1.15.x.md
@@ -14,6 +14,9 @@ Comprehensive health dashboard with config-driven metric cards, collapsible cate
- **Deep-linkable health dashboard** — `useSearchParams` for `range` and `section` URL params (e.g. `?range=30d&section=walking`)
- **Alcohol/HRV correlation moved to Alcohol tab** — AlcoholHrvCorrelation chart now lives alongside the consumption chart with synced view range
+- **Apple Health clinical records import** — ZIP uploads now extract FHIR R4 JSON files from `clinical_records/`, parse lab observations with LOINC code mapping (~70 codes), and merge results into blood-tests.json with non-destructive merge (existing manual entries preserved)
+- **Extended blood test reference ranges** — added 23 new metric keys to `REFERENCE_RANGES` (electrolytes, liver panel, CBC differentials, lipid ratios) with proper categorization in the Blood & Body tab
+
## Improvements
- **Smart aggregation for sum metrics** — refactored `getDailyAggregates` to use a `SUM_METRICS` set instead of hardcoded `metricName === 'step_count'`; covers active energy, basal energy, flights climbed, exercise time, stand time, walking/cycling distance, and time in daylight
diff --git a/client/src/components/meatspace/BloodTestCard.jsx b/client/src/components/meatspace/BloodTestCard.jsx
index 202aeb9186..8cc7ae5c44 100644
--- a/client/src/components/meatspace/BloodTestCard.jsx
+++ b/client/src/components/meatspace/BloodTestCard.jsx
@@ -49,11 +49,22 @@ export default function BloodTestCard({ test }) {
}
function getCategoryForKey(key) {
- const lipids = ['cholesterol', 'hdl', 'ldl', 'triglycerides'];
- const cbc = ['wbc', 'rbc', 'hemoglobin', 'hematocrit', 'platelets'];
- const thyroid = ['tsh'];
+ const metabolic = [
+ 'glucose', 'bun', 'creatinine', 'egfr', 'na', 'k', 'ci', 'co2',
+ 'calcium', 'protein', 'albumin', 'globulin', 'a_g_ratio', 'bilirubin',
+ 'bili_direct', 'alk_phos', 'sgot_ast', 'alt', 'hba1c', 'anion_gap', 'apoB'
+ ];
+ const lipids = ['cholesterol', 'hdl', 'ldl', 'triglycerides', 'chol_hdl_ratio', 'non_hdl_col'];
+ const cbc = [
+ 'wbc', 'rbc', 'hemoglobin', 'hematocrit', 'platelets',
+ 'mcv', 'mch', 'mchc', 'rdw', 'mpv',
+ 'neutrophils_pct', 'lymphocytes_pct', 'monocytes_pct', 'eosinophils_pct', 'basophils_pct',
+ 'abs_neutrophils', 'abs_lymphocytes', 'abs_monocytes', 'abs_eosinophils', 'abs_basophils'
+ ];
+ const thyroid = ['tsh', 'free_t4', 'free_t3'];
+ if (metabolic.includes(key)) return 'Metabolic Panel';
if (lipids.includes(key)) return 'Lipids';
if (cbc.includes(key)) return 'CBC';
if (thyroid.includes(key)) return 'Thyroid';
- return 'Metabolic Panel';
+ return 'Other';
}
diff --git a/client/src/components/meatspace/HealthCategorySection.jsx b/client/src/components/meatspace/HealthCategorySection.jsx
index 54e1afb303..666d10a529 100644
--- a/client/src/components/meatspace/HealthCategorySection.jsx
+++ b/client/src/components/meatspace/HealthCategorySection.jsx
@@ -6,6 +6,7 @@ import SleepCard from './SleepCard';
export default function HealthCategorySection({ category, from, to, expanded, onToggle, availableMetrics }) {
const [metricData, setMetricData] = useState({});
+ const [latestValues, setLatestValues] = useState({});
const [loading, setLoading] = useState(false);
const lastRangeRef = useRef(null);
@@ -31,10 +32,21 @@ export default function HealthCategorySection({ category, from, to, expanded, on
).then(results => {
if (cancelled) return;
const dataMap = {};
- for (const r of results) dataMap[r.key] = r.data;
+ const emptyMetrics = [];
+ for (const r of results) {
+ dataMap[r.key] = r.data;
+ if (r.data.length === 0) emptyMetrics.push(r.key);
+ }
setMetricData(dataMap);
lastRangeRef.current = rangeKey;
setLoading(false);
+
+ // Fetch latest values for metrics with no data in this range
+ if (emptyMetrics.length > 0) {
+ api.getLatestHealthMetrics(emptyMetrics)
+ .then(latest => { if (!cancelled) setLatestValues(prev => ({ ...prev, ...latest })); })
+ .catch(() => {});
+ }
});
return () => { cancelled = true; };
@@ -59,7 +71,13 @@ export default function HealthCategorySection({ category, from, to, expanded, on
metric.key === 'sleep_analysis' ? (
<SleepCard key={metric.key} data={metricData[metric.key] ?? []} loading={loading} />
) : (
- <MetricCard key={metric.key} data={metricData[metric.key] ?? []} loading={loading} config={metric} />
+ <MetricCard
+ key={metric.key}
+ data={metricData[metric.key] ?? []}
+ loading={loading}
+ config={metric}
+ latestValue={latestValues[metric.key] ?? null}
+ />
)
)}
</div>
diff --git a/client/src/components/meatspace/MetricCard.jsx b/client/src/components/meatspace/MetricCard.jsx
index 7da60dfb90..c4455bbea7 100644
--- a/client/src/components/meatspace/MetricCard.jsx
+++ b/client/src/components/meatspace/MetricCard.jsx
@@ -2,7 +2,7 @@ import {
LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer
} from 'recharts';
-export default function MetricCard({ data = [], loading = false, config }) {
+export default function MetricCard({ data = [], loading = false, config, latestValue }) {
const { label, unit, color, aggregation, formatValue } = config;
const isSumMetric = aggregation === 'sum';
@@ -23,11 +23,23 @@ export default function MetricCard({ data = [], loading = false, config }) {
const summaryLabel = isSumMetric ? `avg daily ${unit}` : unit;
+ // Show latest recorded value when no data in current range
+ const showLatest = displayValue == null && latestValue?.date;
+ const latestDisplay = showLatest
+ ? (formatValue ? formatValue(latestValue.value) : latestValue.value)
+ : null;
+
return (
<div className="bg-port-card border border-port-border rounded-xl p-6">
<h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">{label}</h3>
{loading ? (
<div className="flex items-center justify-center h-40 text-gray-600 text-sm">Loading...</div>
+ ) : showLatest ? (
+ <div className="flex flex-col items-center justify-center h-40">
+ <span className="text-3xl font-bold text-white font-mono">{latestDisplay}</span>
+ <span className="text-sm text-gray-500 mt-1">{unit}</span>
+ <span className="text-xs text-gray-600 mt-2">last recorded {latestValue.date}</span>
+ </div>
) : displayValue == null ? (
<div className="flex items-center justify-center h-40 text-gray-600 text-sm">No {label.toLowerCase()} data available</div>
) : (
diff --git a/client/src/components/meatspace/constants.js b/client/src/components/meatspace/constants.js
index 9abdee5f23..fa606953fd 100644
--- a/client/src/components/meatspace/constants.js
+++ b/client/src/components/meatspace/constants.js
@@ -57,6 +57,32 @@ export const REFERENCE_RANGES = {
platelets: { min: 150, max: 400, unit: 'K/uL', label: 'Platelets' },
// Thyroid
tsh: { min: 0.4, max: 4.0, unit: 'mIU/L', label: 'TSH' },
+ // Metabolic Panel (extended)
+ na: { min: 136, max: 144, unit: 'mmol/L', label: 'Sodium' },
+ k: { min: 3.5, max: 5.2, unit: 'mmol/L', label: 'Potassium' },
+ ci: { min: 98, max: 106, unit: 'mmol/L', label: 'Chloride' },
+ co2: { min: 22, max: 32, unit: 'mmol/L', label: 'CO2' },
+ calcium: { min: 8.6, max: 10.3, unit: 'mg/dL', label: 'Calcium' },
+ protein: { min: 6.0, max: 8.3, unit: 'g/dL', label: 'Total Protein' },
+ albumin: { min: 3.5, max: 5.5, unit: 'g/dL', label: 'Albumin' },
+ globulin: { min: 1.5, max: 4.5, unit: 'g/dL', label: 'Globulin' },
+ a_g_ratio: { min: 1.0, max: 2.5, unit: '', label: 'A/G Ratio' },
+ bilirubin: { min: 0.1, max: 1.2, unit: 'mg/dL', label: 'Bilirubin' },
+ bili_direct: { min: 0.0, max: 0.5, unit: 'mg/dL', label: 'Bilirubin Direct' },
+ alk_phos: { min: 36, max: 130, unit: 'U/L', label: 'Alkaline Phosphatase' },
+ sgot_ast: { min: 10, max: 40, unit: 'U/L', label: 'AST (SGOT)' },
+ alt: { min: 7, max: 56, unit: 'U/L', label: 'ALT (SGPT)' },
+ hba1c: { min: 4.0, max: 5.6, unit: '%', label: 'HbA1c' },
+ anion_gap: { min: 3, max: 12, unit: 'mmol/L', label: 'Anion Gap' },
+ // Lipids (extended)
+ chol_hdl_ratio: { min: 0, max: 5.0, unit: '', label: 'Chol/HDL Ratio' },
+ non_hdl_col: { min: 0, max: 130, unit: 'mg/dL', label: 'Non-HDL Cholesterol' },
+ // CBC (extended)
+ mcv: { min: 80, max: 100, unit: 'fL', label: 'MCV' },
+ mch: { min: 27, max: 33, unit: 'pg', label: 'MCH' },
+ mchc: { min: 32, max: 36, unit: 'g/dL', label: 'MCHC' },
+ rdw: { min: 11.0, max: 15.0, unit: '%', label: 'RDW' },
+ mpv: { min: 7.5, max: 12.5, unit: 'fL', label: 'MPV' },
// Other
homocysteine: { min: 5, max: 15, unit: 'umol/L', label: 'Homocysteine' }
};
diff --git a/client/src/components/meatspace/tabs/OverviewTab.jsx b/client/src/components/meatspace/tabs/OverviewTab.jsx
index ef5c43bcf6..8df4e01a4e 100644
--- a/client/src/components/meatspace/tabs/OverviewTab.jsx
+++ b/client/src/components/meatspace/tabs/OverviewTab.jsx
@@ -160,6 +160,7 @@ export default function OverviewTab() {
const [data, setData] = useState(null);
const [alcohol, setAlcohol] = useState(null);
const [body, setBody] = useState(null);
+ const [healthBody, setHealthBody] = useState(null);
const [blood, setBlood] = useState(null);
const [epigenetic, setEpigenetic] = useState(null);
const [eyes, setEyes] = useState(null);
@@ -167,17 +168,19 @@ export default function OverviewTab() {
const navigate = useNavigate();
const fetchData = useCallback(async () => {
- const [overview, alc, bod, bld, epi, eye] = await Promise.all([
+ const [overview, alc, bod, bld, epi, eye, hBody] = await Promise.all([
api.getMeatspaceOverview().catch(() => null),
api.getAlcoholSummary().catch(() => null),
api.getBodyHistory().catch(() => null),
api.getBloodTests().catch(() => null),
api.getEpigeneticTests().catch(() => null),
api.getEyeExams().catch(() => null),
+ api.getLatestHealthMetrics(['body_mass', 'body_fat_percentage', 'lean_body_mass']).catch(() => null),
]);
setData(overview);
setAlcohol(alc);
setBody(bod);
+ setHealthBody(hBody);
setBlood(bld);
setEpigenetic(epi);
setEyes(eye);
@@ -203,7 +206,15 @@ export default function OverviewTab() {
}
const { deathClock, lev, summary } = data;
- const latestBody = Array.isArray(body) ? body[body.length - 1] : null;
+ const manualBody = Array.isArray(body) ? body.findLast(b => b.weightLbs) ?? null : null;
+ // Use Apple Health body data if it's more recent than manual entries
+ const hWeight = healthBody?.body_mass;
+ const hFat = healthBody?.body_fat_percentage;
+ const hLean = healthBody?.lean_body_mass;
+ const useHealth = hWeight?.date && (!manualBody?.date || hWeight.date > manualBody.date);
+ const latestBody = useHealth
+ ? { weightLbs: Math.round(hWeight.value * 10) / 10, fatPct: hFat ? Math.round(hFat.value * 1000) / 10 : null, leanLbs: hLean ? Math.round(hLean.value * 10) / 10 : null }
+ : manualBody;
const latestBlood = blood?.tests?.[blood.tests.length - 1] ?? null;
const latestEpigenetic = epigenetic?.tests?.[epigenetic.tests.length - 1] ?? null;
const latestEye = eyes?.exams?.[eyes.exams.length - 1] ?? null;
@@ -268,7 +279,8 @@ export default function OverviewTab() {
metrics={[
{ label: 'Weight', value: latestBody?.weightLbs ? `${latestBody.weightLbs} lbs` : '—' },
{ label: 'Body fat', value: latestBody?.fatPct != null ? `${latestBody.fatPct}%` : '—' },
- { label: 'Muscle', value: latestBody?.musclePct != null ? `${latestBody.musclePct}%` : '—' },
+ { label: latestBody?.leanLbs ? 'Lean' : 'Muscle',
+ value: latestBody?.leanLbs ? `${latestBody.leanLbs} lbs` : latestBody?.musclePct != null ? `${latestBody.musclePct}%` : '—' },
]}
/>
<HealthTile
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 137c3728ba..46a2fecfb8 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -61,6 +61,8 @@ export const getAppleHealthSummary = (metricName, from, to) => {
return request(`/health/metrics/${metricName}?${params}`);
};
export const getAvailableHealthMetrics = () => request('/health/metrics/available');
+export const getLatestHealthMetrics = (metricNames) =>
+ request(`/health/metrics/latest?metrics=${metricNames.join(',')}`);
export const getAppleHealthRange = () => request('/health/range');
export const getAppleHealthCorrelation = (from, to) => {
const params = new URLSearchParams();
diff --git a/package-lock.json b/package-lock.json
index 0703f60a5e..0d4cb060da 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos",
- "version": "1.15.1",
+ "version": "1.16.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos",
- "version": "1.15.1",
+ "version": "1.16.0",
"license": "MIT",
"dependencies": {
"express": "^4.21.2",
diff --git a/package.json b/package.json
index 91c7f0a4f1..c8dd30c47e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "portos",
- "version": "1.15.1",
+ "version": "1.16.0",
"private": true,
"description": "Local dev machine App OS portal",
"author": "Adam Eivy (@antic|@atomantic)",
diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.js
index 8d98afad48..b8b93d51aa 100644
--- a/server/routes/appleHealth.js
+++ b/server/routes/appleHealth.js
@@ -9,12 +9,14 @@ 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 { importClinicalRecords } from '../services/appleHealthClinical.js';
import {
getMetricSummary,
getDailyAggregates,
getAvailableDateRange,
getCorrelationData,
- getAvailableMetrics
+ getAvailableMetrics,
+ getLatestMetricValues
} from '../services/appleHealthQuery.js';
const isZip = (file) =>
@@ -62,6 +64,15 @@ router.get('/metrics/available', asyncHandler(async (req, res) => {
res.json(metrics);
}));
+// GET /api/health/metrics/latest
+// Returns most recent recorded value for each requested metric
+router.get('/metrics/latest', asyncHandler(async (req, res) => {
+ const metrics = req.query.metrics?.split(',').filter(Boolean) ?? [];
+ if (metrics.length === 0) return res.json({});
+ const latest = await getLatestMetricValues(metrics);
+ res.json(latest);
+}));
+
// GET /api/health/metrics/:metricName
// Returns summary stats for a metric over a date range
router.get('/metrics/:metricName', asyncHandler(async (req, res) => {
@@ -102,36 +113,60 @@ router.post('/import/xml', upload.single('file'), asyncHandler(async (req, res)
let filePath = req.file?.path;
if (!filePath) throw new ServerError('No file uploaded', { status: 400, code: 'BAD_REQUEST' });
- // If ZIP, extract export.xml to a temp file
+ // If ZIP, extract export.xml to a temp file and collect clinical records
+ let clinicalJsons = [];
+
if (req.file.originalname.endsWith('.zip') || isZip(req.file)) {
const xmlPath = join(tmpdir(), `apple-health-${Date.now()}.xml`);
- let found = false;
+ let foundXml = false;
+ let xmlWriteFinished = false;
await new Promise((resolve, reject) => {
let settled = false;
const settle = (fn) => (...args) => { if (!settled) { settled = true; fn(...args); } };
+
createReadStream(filePath)
.pipe(unzipParse())
.on('entry', (entry) => {
if (entry.path === 'apple_health_export/export.xml' || entry.path === 'export.xml') {
- found = true;
- entry.pipe(createWriteStream(xmlPath))
- .on('finish', settle(resolve))
+ foundXml = true;
+ const ws = createWriteStream(xmlPath);
+ entry.pipe(ws)
+ .on('finish', () => { xmlWriteFinished = true; })
.on('error', settle(reject));
+ } else if (entry.path.includes('clinical_records/') && entry.path.endsWith('.json')) {
+ // Buffer clinical record JSON files (~1-5KB each)
+ const chunks = [];
+ entry.on('data', (chunk) => chunks.push(chunk));
+ entry.on('end', () => clinicalJsons.push(Buffer.concat(chunks).toString('utf-8')));
} else {
entry.autodrain();
}
})
- .on('close', () => { if (!found) settle(reject)(new ServerError('ZIP does not contain export.xml', { status: 400, code: 'BAD_REQUEST' })); })
+ .on('close', () => {
+ if (!foundXml) return settle(reject)(new ServerError('ZIP does not contain export.xml', { status: 400, code: 'BAD_REQUEST' }));
+ // Wait briefly for XML write stream to finish if close fires first
+ if (xmlWriteFinished) return settle(resolve)();
+ const check = setInterval(() => { if (xmlWriteFinished) { clearInterval(check); settle(resolve)(); } }, 50);
+ setTimeout(() => { clearInterval(check); settle(resolve)(); }, 5000);
+ })
.on('error', settle(reject));
});
await fs.unlink(filePath);
filePath = xmlPath;
+ console.log(`📋 Found ${clinicalJsons.length} clinical record files in ZIP`);
}
const result = await importAppleHealthXml(filePath, io);
- res.json(result);
+
+ // Import clinical records if any were found
+ let clinicalResult = null;
+ if (clinicalJsons.length > 0) {
+ clinicalResult = await importClinicalRecords(clinicalJsons, io);
+ }
+
+ res.json({ ...result, ...(clinicalResult && { clinical: clinicalResult }) });
}));
export default router;
diff --git a/server/services/appleHealthClinical.js b/server/services/appleHealthClinical.js
new file mode 100644
index 0000000000..4bce05f5f2
--- /dev/null
+++ b/server/services/appleHealthClinical.js
@@ -0,0 +1,302 @@
+/**
+ * Apple Health Clinical Records Service
+ *
+ * Parses FHIR R4 JSON files from Apple Health export's clinical_records/ directory,
+ * extracts lab observations, maps LOINC codes to standardized keys, and merges
+ * into blood-tests.json.
+ */
+
+import { safeJSONParse } from '../lib/fileUtils.js';
+import { getBloodTests } from './meatspaceHealth.js';
+import { writeFile } from 'fs/promises';
+import { join } from 'path';
+import { PATHS, ensureDir } from '../lib/fileUtils.js';
+
+const BLOOD_TESTS_FILE = join(PATHS.meatspace, 'blood-tests.json');
+
+// === LOINC Code → Key Mapping ===
+
+export const LOINC_TO_KEY = {
+ // Metabolic Panel
+ '2345-7': 'glucose',
+ '2339-0': 'glucose', // Glucose [Mass/volume] in Blood
+ '3094-0': 'bun',
+ '2160-0': 'creatinine',
+ '48642-3': 'egfr',
+ '33914-3': 'egfr',
+ '62238-1': 'egfr',
+ '77147-7': 'egfr',
+ '88293-6': 'egfr',
+ '2951-2': 'na',
+ '2823-3': 'k',
+ '2075-0': 'ci',
+ '2028-9': 'co2',
+ '17861-6': 'calcium',
+ '2885-2': 'protein',
+ '1751-7': 'albumin',
+ '10834-0': 'globulin',
+ '1759-0': 'a_g_ratio',
+ '1975-2': 'bilirubin',
+ '1968-7': 'bili_direct',
+ '6768-6': 'alk_phos',
+ '1920-8': 'sgot_ast',
+ '1742-6': 'alt',
+ '4548-4': 'hba1c',
+ '17856-6': 'hba1c',
+ '33037-3': 'anion_gap',
+ '41653-7': 'glucose', // Glucose [Mass/volume] in Capillary blood
+
+ // Lipids
+ '2093-3': 'cholesterol',
+ '2085-9': 'hdl',
+ '2089-1': 'ldl',
+ '13457-7': 'ldl',
+ '18262-6': 'ldl', // LDL Cholesterol (calculated)
+ '2571-8': 'triglycerides',
+ '9830-1': 'chol_hdl_ratio',
+ '43396-1': 'non_hdl_col',
+
+ // CBC
+ '6690-2': 'wbc',
+ '789-8': 'rbc',
+ '718-7': 'hemoglobin',
+ '4544-3': 'hematocrit',
+ '777-3': 'platelets',
+ '787-2': 'mcv',
+ '785-6': 'mch',
+ '786-4': 'mchc',
+ '788-0': 'rdw',
+ '32623-1': 'mpv',
+ '770-8': 'neutrophils_pct',
+ '736-9': 'lymphocytes_pct',
+ '5905-5': 'monocytes_pct',
+ '713-8': 'eosinophils_pct',
+ '706-2': 'basophils_pct',
+ '751-8': 'abs_neutrophils',
+ '731-0': 'abs_lymphocytes',
+ '742-7': 'abs_monocytes',
+ '711-2': 'abs_eosinophils',
+ '704-7': 'abs_basophils',
+
+ // Thyroid
+ '3016-3': 'tsh',
+ '3024-7': 'free_t4',
+ '3053-6': 'free_t3',
+
+ // Other common labs
+ '1884-6': 'apoB',
+ '13965-9': 'homocysteine',
+ '2532-0': 'ldh',
+ '2276-4': 'ferritin',
+ '2498-4': 'iron',
+ '2502-3': 'iron_sat',
+ '2000-8': 'calcium_ionized',
+ '14879-1': 'phosphorus',
+ '19123-9': 'magnesium',
+ '2157-6': 'ck',
+ '14804-9': 'uric_acid',
+ '30239-8': 'vitamin_d',
+ '2132-9': 'vitamin_b12',
+ '2284-8': 'folate',
+ '4548-4': 'hba1c',
+ '1558-6': 'glucose_fasting',
+ '2947-0': 'sodium_urine',
+};
+
+// === Pure Functions ===
+
+/**
+ * Convert a display name to a snake_case key.
+ * Strips bracketed content (e.g. "[Mass/volume]") and common suffixes
+ * like "in Blood" or "in Serum" before converting.
+ */
+export function toSnakeCase(str) {
+ if (!str) return '';
+ return str
+ .replace(/\[.*?\]/g, '') // strip [bracketed content]
+ .replace(/\s+in\s+(Blood|Serum|Plasma).*$/i, '') // strip "in Blood/Serum/Plasma..."
+ .replace(/\s+by\s+.+$/i, '') // strip "by <method>"
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '_') // non-alphanumeric → underscore
+ .replace(/^_|_$/g, '') // trim leading/trailing underscores
+ .replace(/_+/g, '_'); // collapse multiple underscores
+}
+
+/**
+ * Parse a single FHIR JSON string into a lab result.
+ * Returns { date, key, value, unit, refLow, refHigh, label } or null.
+ */
+export function parseFhirLabResult(jsonStr) {
+ const resource = safeJSONParse(jsonStr, null);
+ if (!resource) return null;
+
+ // Must be an Observation
+ if (resource.resourceType !== 'Observation') return null;
+
+ // Must be a laboratory category
+ const categories = resource.category || [];
+ const isLab = categories.some(cat =>
+ cat.coding?.some(c => c.code === 'laboratory')
+ );
+ if (!isLab) return null;
+
+ // Skip cancelled/entered-in-error
+ if (resource.status === 'cancelled' || resource.status === 'entered-in-error') return null;
+
+ // Must have a numeric valueQuantity
+ const vq = resource.valueQuantity;
+ if (!vq || typeof vq.value !== 'number') return null;
+
+ // Extract date (effectiveDateTime or issued)
+ const dateRaw = resource.effectiveDateTime || resource.issued;
+ if (!dateRaw) return null;
+ const date = dateRaw.substring(0, 10); // YYYY-MM-DD
+
+ // Extract LOINC code and display name
+ const coding = resource.code?.coding || [];
+ const loincEntry = coding.find(c => c.system?.includes('loinc'));
+ const loincCode = loincEntry?.code;
+ const displayName = resource.code?.text || loincEntry?.display || '';
+
+ // Map to key: LOINC lookup first, then fallback to snake_case of display name
+ const key = (loincCode && LOINC_TO_KEY[loincCode]) || toSnakeCase(displayName);
+ if (!key) return null;
+
+ // Extract reference range if available
+ const refRange = resource.referenceRange?.[0];
+ const refLow = refRange?.low?.value ?? null;
+ const refHigh = refRange?.high?.value ?? null;
+
+ return {
+ date,
+ key,
+ value: vq.value,
+ unit: vq.unit || vq.code || '',
+ refLow,
+ refHigh,
+ label: displayName || key
+ };
+}
+
+/**
+ * Process an array of FHIR JSON strings into grouped blood test data.
+ * Returns { tests, referenceRanges, totalParsed, totalSkipped }.
+ */
+export function processClinicalRecords(jsonStrings) {
+ const byDate = {}; // date → { key: value, ... }
+ const refRanges = {}; // key → { min, max, unit, label }
+ let totalParsed = 0;
+ let totalSkipped = 0;
+
+ for (const jsonStr of jsonStrings) {
+ const result = parseFhirLabResult(jsonStr);
+ if (!result) {
+ totalSkipped++;
+ continue;
+ }
+
+ totalParsed++;
+ const { date, key, value, unit, refLow, refHigh, label } = result;
+
+ if (!byDate[date]) byDate[date] = {};
+ byDate[date][key] = value;
+
+ // Collect reference ranges (first seen wins)
+ if ((refLow != null || refHigh != null) && !refRanges[key]) {
+ refRanges[key] = {
+ ...(refLow != null && { min: refLow }),
+ ...(refHigh != null && { max: refHigh }),
+ unit,
+ label
+ };
+ }
+ }
+
+ // Convert byDate map to sorted array of test entries
+ const tests = Object.entries(byDate)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([date, values]) => ({ date, ...values }));
+
+ return { tests, referenceRanges: refRanges, totalParsed, totalSkipped };
+}
+
+/**
+ * Pure merge: combine existing blood test data with FHIR-imported data.
+ * For existing dates, add new keys only (don't overwrite manual entries).
+ * For new dates, add the whole entry.
+ * Merge reference ranges (don't overwrite existing).
+ */
+export function mergeBloodTests(existing, fhirData) {
+ const existingTests = [...(existing.tests || [])];
+ const existingRanges = { ...(existing.referenceRanges || {}) };
+
+ const existingByDate = new Map(existingTests.map(t => [t.date, t]));
+
+ for (const fhirTest of fhirData.tests) {
+ const { date, ...fhirValues } = fhirTest;
+ const existingEntry = existingByDate.get(date);
+
+ if (existingEntry) {
+ // Add new keys only — don't overwrite existing manual entries
+ for (const [key, value] of Object.entries(fhirValues)) {
+ if (existingEntry[key] === undefined) {
+ existingEntry[key] = value;
+ }
+ }
+ } else {
+ existingTests.push(fhirTest);
+ existingByDate.set(date, fhirTest);
+ }
+ }
+
+ // Merge reference ranges — don't overwrite existing
+ for (const [key, range] of Object.entries(fhirData.referenceRanges)) {
+ if (!existingRanges[key]) {
+ existingRanges[key] = range;
+ }
+ }
+
+ // Sort by date
+ existingTests.sort((a, b) => a.date.localeCompare(b.date));
+
+ return { tests: existingTests, referenceRanges: existingRanges };
+}
+
+// === Orchestrator ===
+
+/**
+ * Import clinical records from FHIR JSON strings.
+ * Reads existing blood-tests.json, merges FHIR data, writes back, emits progress.
+ */
+export async function importClinicalRecords(jsonStrings, io) {
+ if (!jsonStrings?.length) return { clinicalRecords: 0, newDates: 0, newValues: 0 };
+
+ io?.emit?.('health:import:progress', { stage: 'clinical', message: `Processing ${jsonStrings.length} clinical records...` });
+
+ const fhirData = processClinicalRecords(jsonStrings);
+ const existing = await getBloodTests();
+ const existingDates = new Set(existing.tests.map(t => t.date));
+
+ const merged = mergeBloodTests(existing, fhirData);
+
+ // Count what changed
+ const newDates = merged.tests.filter(t => !existingDates.has(t.date)).length;
+ const newValues = fhirData.totalParsed;
+
+ await ensureDir(PATHS.meatspace);
+ await writeFile(BLOOD_TESTS_FILE, JSON.stringify(merged, null, 2));
+
+ const summary = {
+ clinicalRecords: jsonStrings.length,
+ labsParsed: fhirData.totalParsed,
+ labsSkipped: fhirData.totalSkipped,
+ newDates,
+ totalDates: merged.tests.length
+ };
+
+ console.log(`🧪 Clinical records imported: ${fhirData.totalParsed} labs from ${fhirData.tests.length} dates (${newDates} new)`);
+ io?.emit?.('health:import:progress', { stage: 'clinical_done', ...summary });
+
+ return summary;
+}
diff --git a/server/services/appleHealthClinical.test.js b/server/services/appleHealthClinical.test.js
new file mode 100644
index 0000000000..038a83d5ba
--- /dev/null
+++ b/server/services/appleHealthClinical.test.js
@@ -0,0 +1,355 @@
+import { describe, it, expect } from 'vitest';
+
+// Inline pure functions to avoid mocking file I/O (matches project test pattern)
+// These are copies of the functions from appleHealthClinical.js
+
+const LOINC_TO_KEY = {
+ '2345-7': 'glucose',
+ '3094-0': 'bun',
+ '2160-0': 'creatinine',
+ '48642-3': 'egfr',
+ '2951-2': 'na',
+ '2823-3': 'k',
+ '2075-0': 'ci',
+ '2028-9': 'co2',
+ '2093-3': 'cholesterol',
+ '2085-9': 'hdl',
+ '2089-1': 'ldl',
+ '2571-8': 'triglycerides',
+ '6690-2': 'wbc',
+ '789-8': 'rbc',
+ '718-7': 'hemoglobin',
+ '3016-3': 'tsh',
+ '4548-4': 'hba1c',
+};
+
+function toSnakeCase(str) {
+ if (!str) return '';
+ return str
+ .replace(/\[.*?\]/g, '')
+ .replace(/\s+in\s+(Blood|Serum|Plasma).*$/i, '')
+ .replace(/\s+by\s+.+$/i, '')
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '_')
+ .replace(/^_|_$/g, '')
+ .replace(/_+/g, '_');
+}
+
+function parseFhirLabResult(jsonStr) {
+ let resource;
+ try { resource = JSON.parse(jsonStr); } catch { return null; }
+ if (!resource) return null;
+ if (resource.resourceType !== 'Observation') return null;
+ const categories = resource.category || [];
+ const isLab = categories.some(cat =>
+ cat.coding?.some(c => c.code === 'laboratory')
+ );
+ if (!isLab) return null;
+ if (resource.status === 'cancelled' || resource.status === 'entered-in-error') return null;
+ const vq = resource.valueQuantity;
+ if (!vq || typeof vq.value !== 'number') return null;
+ const dateRaw = resource.effectiveDateTime || resource.issued;
+ if (!dateRaw) return null;
+ const date = dateRaw.substring(0, 10);
+ const coding = resource.code?.coding || [];
+ const loincEntry = coding.find(c => c.system?.includes('loinc'));
+ const loincCode = loincEntry?.code;
+ const displayName = resource.code?.text || loincEntry?.display || '';
+ const key = (loincCode && LOINC_TO_KEY[loincCode]) || toSnakeCase(displayName);
+ if (!key) return null;
+ const refRange = resource.referenceRange?.[0];
+ const refLow = refRange?.low?.value ?? null;
+ const refHigh = refRange?.high?.value ?? null;
+ return { date, key, value: vq.value, unit: vq.unit || vq.code || '', refLow, refHigh, label: displayName || key };
+}
+
+function processClinicalRecords(jsonStrings) {
+ const byDate = {};
+ const refRanges = {};
+ let totalParsed = 0;
+ let totalSkipped = 0;
+ for (const jsonStr of jsonStrings) {
+ const result = parseFhirLabResult(jsonStr);
+ if (!result) { totalSkipped++; continue; }
+ totalParsed++;
+ const { date, key, value, unit, refLow, refHigh, label } = result;
+ if (!byDate[date]) byDate[date] = {};
+ byDate[date][key] = value;
+ if ((refLow != null || refHigh != null) && !refRanges[key]) {
+ refRanges[key] = {
+ ...(refLow != null && { min: refLow }),
+ ...(refHigh != null && { max: refHigh }),
+ unit, label
+ };
+ }
+ }
+ const tests = Object.entries(byDate)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([date, values]) => ({ date, ...values }));
+ return { tests, referenceRanges: refRanges, totalParsed, totalSkipped };
+}
+
+function mergeBloodTests(existing, fhirData) {
+ const existingTests = [...(existing.tests || [])];
+ const existingRanges = { ...(existing.referenceRanges || {}) };
+ const existingByDate = new Map(existingTests.map(t => [t.date, t]));
+ for (const fhirTest of fhirData.tests) {
+ const { date, ...fhirValues } = fhirTest;
+ const existingEntry = existingByDate.get(date);
+ if (existingEntry) {
+ for (const [key, value] of Object.entries(fhirValues)) {
+ if (existingEntry[key] === undefined) existingEntry[key] = value;
+ }
+ } else {
+ existingTests.push(fhirTest);
+ existingByDate.set(date, fhirTest);
+ }
+ }
+ for (const [key, range] of Object.entries(fhirData.referenceRanges)) {
+ if (!existingRanges[key]) existingRanges[key] = range;
+ }
+ existingTests.sort((a, b) => a.date.localeCompare(b.date));
+ return { tests: existingTests, referenceRanges: existingRanges };
+}
+
+// === Test Helpers ===
+
+function makeFhirObservation({ code, display, value, unit, date, refLow, refHigh, status, category } = {}) {
+ return JSON.stringify({
+ resourceType: 'Observation',
+ status: status || 'final',
+ category: [{ coding: [{ system: 'http://terminology.hl7.org/CodeSystem/observation-category', code: category || 'laboratory' }] }],
+ code: { coding: [{ system: 'http://loinc.org', code, display }], text: display },
+ effectiveDateTime: date || '2025-01-15T10:30:00Z',
+ valueQuantity: { value, unit: unit || 'mg/dL', system: 'http://unitsofmeasure.org' },
+ ...(refLow != null || refHigh != null ? {
+ referenceRange: [{
+ ...(refLow != null && { low: { value: refLow, unit: unit || 'mg/dL' } }),
+ ...(refHigh != null && { high: { value: refHigh, unit: unit || 'mg/dL' } })
+ }]
+ } : {})
+ });
+}
+
+// =============================================================================
+// toSnakeCase TESTS
+// =============================================================================
+
+describe('toSnakeCase', () => {
+ it('converts display name to snake_case', () => {
+ expect(toSnakeCase('Glucose')).toBe('glucose');
+ });
+
+ it('strips bracketed content', () => {
+ expect(toSnakeCase('Glucose [Mass/volume] in Blood')).toBe('glucose');
+ });
+
+ it('strips "in Serum" suffix', () => {
+ expect(toSnakeCase('Creatinine in Serum or Plasma')).toBe('creatinine');
+ });
+
+ it('strips "by method" suffix', () => {
+ expect(toSnakeCase('LDL Cholesterol by calculation')).toBe('ldl_cholesterol');
+ });
+
+ it('handles empty/null input', () => {
+ expect(toSnakeCase('')).toBe('');
+ expect(toSnakeCase(null)).toBe('');
+ expect(toSnakeCase(undefined)).toBe('');
+ });
+
+ it('collapses multiple non-alpha chars', () => {
+ expect(toSnakeCase('A/G Ratio')).toBe('a_g_ratio');
+ });
+});
+
+// =============================================================================
+// parseFhirLabResult TESTS
+// =============================================================================
+
+describe('parseFhirLabResult', () => {
+ it('parses a valid lab observation with LOINC code', () => {
+ const json = makeFhirObservation({ code: '2345-7', display: 'Glucose', value: 95, refLow: 70, refHigh: 99 });
+ const result = parseFhirLabResult(json);
+ expect(result).toEqual({
+ date: '2025-01-15',
+ key: 'glucose',
+ value: 95,
+ unit: 'mg/dL',
+ refLow: 70,
+ refHigh: 99,
+ label: 'Glucose'
+ });
+ });
+
+ it('uses snake_case fallback for unmapped LOINC codes', () => {
+ const json = makeFhirObservation({ code: '99999-9', display: 'Vitamin D [Mass/volume] in Serum', value: 45, unit: 'ng/mL' });
+ const result = parseFhirLabResult(json);
+ expect(result.key).toBe('vitamin_d');
+ });
+
+ it('returns null for non-Observation resources', () => {
+ const json = JSON.stringify({ resourceType: 'Patient', name: [{ family: 'Doe' }] });
+ expect(parseFhirLabResult(json)).toBeNull();
+ });
+
+ it('returns null for non-laboratory observations', () => {
+ const json = makeFhirObservation({ code: '2345-7', display: 'Glucose', value: 95, category: 'vital-signs' });
+ expect(parseFhirLabResult(json)).toBeNull();
+ });
+
+ it('returns null for cancelled observations', () => {
+ const json = makeFhirObservation({ code: '2345-7', display: 'Glucose', value: 95, status: 'cancelled' });
+ expect(parseFhirLabResult(json)).toBeNull();
+ });
+
+ it('returns null for non-numeric values', () => {
+ const json = JSON.stringify({
+ resourceType: 'Observation',
+ status: 'final',
+ category: [{ coding: [{ code: 'laboratory' }] }],
+ code: { coding: [{ system: 'http://loinc.org', code: '2345-7' }] },
+ effectiveDateTime: '2025-01-15',
+ valueString: 'Negative'
+ });
+ expect(parseFhirLabResult(json)).toBeNull();
+ });
+
+ it('returns null for invalid JSON', () => {
+ expect(parseFhirLabResult('not json')).toBeNull();
+ expect(parseFhirLabResult('')).toBeNull();
+ });
+
+ it('extracts date from effectiveDateTime', () => {
+ const json = makeFhirObservation({ code: '3094-0', display: 'BUN', value: 15, date: '2024-06-20T08:00:00-07:00' });
+ expect(parseFhirLabResult(json).date).toBe('2024-06-20');
+ });
+
+ it('handles missing reference ranges', () => {
+ const json = makeFhirObservation({ code: '2345-7', display: 'Glucose', value: 95 });
+ const result = parseFhirLabResult(json);
+ expect(result.refLow).toBeNull();
+ expect(result.refHigh).toBeNull();
+ });
+});
+
+// =============================================================================
+// processClinicalRecords TESTS
+// =============================================================================
+
+describe('processClinicalRecords', () => {
+ it('groups results by date and collects reference ranges', () => {
+ const jsons = [
+ makeFhirObservation({ code: '2345-7', display: 'Glucose', value: 95, date: '2025-01-15T10:00:00Z', refLow: 70, refHigh: 99 }),
+ makeFhirObservation({ code: '3094-0', display: 'BUN', value: 15, date: '2025-01-15T10:00:00Z', refLow: 7, refHigh: 20 }),
+ makeFhirObservation({ code: '2093-3', display: 'Cholesterol', value: 180, date: '2025-03-01T10:00:00Z', refLow: 0, refHigh: 200 })
+ ];
+
+ const result = processClinicalRecords(jsons);
+ expect(result.tests).toHaveLength(2);
+ expect(result.tests[0]).toEqual({ date: '2025-01-15', glucose: 95, bun: 15 });
+ expect(result.tests[1]).toEqual({ date: '2025-03-01', cholesterol: 180 });
+ expect(result.referenceRanges.glucose).toEqual({ min: 70, max: 99, unit: 'mg/dL', label: 'Glucose' });
+ expect(result.totalParsed).toBe(3);
+ expect(result.totalSkipped).toBe(0);
+ });
+
+ it('counts skipped non-lab records', () => {
+ const jsons = [
+ makeFhirObservation({ code: '2345-7', display: 'Glucose', value: 95 }),
+ JSON.stringify({ resourceType: 'Patient' }),
+ 'invalid json'
+ ];
+
+ const result = processClinicalRecords(jsons);
+ expect(result.totalParsed).toBe(1);
+ expect(result.totalSkipped).toBe(2);
+ });
+
+ it('returns sorted tests by date', () => {
+ const jsons = [
+ makeFhirObservation({ code: '2345-7', display: 'Glucose', value: 100, date: '2025-06-01T10:00:00Z' }),
+ makeFhirObservation({ code: '2345-7', display: 'Glucose', value: 90, date: '2025-01-01T10:00:00Z' })
+ ];
+
+ const result = processClinicalRecords(jsons);
+ expect(result.tests[0].date).toBe('2025-01-01');
+ expect(result.tests[1].date).toBe('2025-06-01');
+ });
+});
+
+// =============================================================================
+// mergeBloodTests TESTS
+// =============================================================================
+
+describe('mergeBloodTests', () => {
+ it('adds new dates from FHIR data', () => {
+ const existing = { tests: [{ date: '2023-09-05', bun: 16 }], referenceRanges: {} };
+ const fhir = {
+ tests: [{ date: '2025-01-15', glucose: 95, bun: 12 }],
+ referenceRanges: { glucose: { min: 70, max: 99, unit: 'mg/dL', label: 'Glucose' } }
+ };
+
+ const result = mergeBloodTests(existing, fhir);
+ expect(result.tests).toHaveLength(2);
+ expect(result.tests[0].date).toBe('2023-09-05');
+ expect(result.tests[1]).toEqual({ date: '2025-01-15', glucose: 95, bun: 12 });
+ });
+
+ it('does not overwrite existing values on same date', () => {
+ const existing = {
+ tests: [{ date: '2023-09-05', bun: 16, tsh: 1.249 }],
+ referenceRanges: { bun: { min: 7, max: 25, label: 'BUN' } }
+ };
+ const fhir = {
+ tests: [{ date: '2023-09-05', bun: 14, glucose: 95 }],
+ referenceRanges: { bun: { min: 7, max: 20, label: 'BUN' }, glucose: { min: 70, max: 99, label: 'Glucose' } }
+ };
+
+ const result = mergeBloodTests(existing, fhir);
+ expect(result.tests).toHaveLength(1);
+ expect(result.tests[0].bun).toBe(16); // kept existing
+ expect(result.tests[0].tsh).toBe(1.249); // kept existing
+ expect(result.tests[0].glucose).toBe(95); // added new
+ });
+
+ it('does not overwrite existing reference ranges', () => {
+ const existing = {
+ tests: [],
+ referenceRanges: { bun: { min: 7, max: 25, label: 'BUN' } }
+ };
+ const fhir = {
+ tests: [],
+ referenceRanges: { bun: { min: 7, max: 20, label: 'BUN' }, glucose: { min: 70, max: 99, label: 'Glucose' } }
+ };
+
+ const result = mergeBloodTests(existing, fhir);
+ expect(result.referenceRanges.bun.max).toBe(25); // kept existing
+ expect(result.referenceRanges.glucose.max).toBe(99); // added new
+ });
+
+ it('handles empty existing data', () => {
+ const existing = { tests: [], referenceRanges: {} };
+ const fhir = {
+ tests: [{ date: '2025-01-15', glucose: 95 }],
+ referenceRanges: { glucose: { min: 70, max: 99, label: 'Glucose' } }
+ };
+
+ const result = mergeBloodTests(existing, fhir);
+ expect(result.tests).toHaveLength(1);
+ expect(result.referenceRanges.glucose).toBeDefined();
+ });
+
+ it('sorts merged tests by date', () => {
+ const existing = { tests: [{ date: '2025-06-01', bun: 10 }], referenceRanges: {} };
+ const fhir = {
+ tests: [{ date: '2024-01-01', glucose: 90 }],
+ referenceRanges: {}
+ };
+
+ const result = mergeBloodTests(existing, fhir);
+ expect(result.tests[0].date).toBe('2024-01-01');
+ expect(result.tests[1].date).toBe('2025-06-01');
+ });
+});
diff --git a/server/services/appleHealthQuery.js b/server/services/appleHealthQuery.js
index 9207639c3e..4ca319c8d0 100644
--- a/server/services/appleHealthQuery.js
+++ b/server/services/appleHealthQuery.js
@@ -230,6 +230,44 @@ export async function getAvailableMetrics() {
.sort((a, b) => a.name.localeCompare(b.name));
}
+// === Latest Values ===
+
+/**
+ * Get the most recent recorded value for each requested metric.
+ * Scans backward from the newest day file until a value is found for each metric.
+ *
+ * @param {string[]} metricNames - Metric names to look up
+ * @returns {Promise<Object>} Map of metricName → { date, value } or null
+ */
+export async function getLatestMetricValues(metricNames) {
+ const dates = await listDayFiles();
+ const result = {};
+ const remaining = new Set(metricNames);
+
+ for (let i = dates.length - 1; i >= 0 && remaining.size > 0; i--) {
+ const dateStr = dates[i];
+ const dayData = await readDayFile(dateStr);
+ const metrics = dayData.metrics ?? {};
+
+ for (const name of [...remaining]) {
+ const points = metrics[name] || metrics[METRIC_ALIASES[name]] || [];
+ if (points.length === 0) continue;
+
+ // Use the last point's qty as the value
+ const lastPoint = points[points.length - 1];
+ const value = lastPoint.qty ?? lastPoint.Avg ?? lastPoint.value ?? null;
+ if (value != null) {
+ result[name] = { date: dateStr, value: Math.round(value * 100) / 100 };
+ remaining.delete(name);
+ }
+ }
+ }
+
+ // Fill nulls for metrics with no data at all
+ for (const name of remaining) result[name] = null;
+ return result;
+}
+
// === Correlation Data ===
/**
diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.js
index 86f749e2b0..4c370d2894 100644
--- a/server/services/meatspaceHealth.js
+++ b/server/services/meatspaceHealth.js
@@ -35,6 +35,11 @@ export async function addBloodTest(test) {
return test;
}
+export async function saveBloodTests(data) {
+ await ensureMeatspaceDir();
+ await writeFile(BLOOD_TESTS_FILE, JSON.stringify(data, null, 2));
+}
+
// === Body Composition ===
export async function getBodyHistory() {