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: blood pressure tracking in MeatSpace → Body (MortalLoom parity)

Adam Eivy74369765c300
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 24f958c852..7c4484c730 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,6 @@
## Added
+- **Blood Pressure tracking in MeatSpace → Body** — feature parity with the MortalLoom iOS/macOS companion app. New Blood Pressure card on the Body tab shows a systolic/diastolic trend chart (with AHA/ACC 2017 guideline reference lines), the latest reading, and its category + estimated life-expectancy impact. Readings are date-upserted so a HealthKit sync on the phone and a manual entry in PortOS on the same day merge into one row. Storage routes through the new `mlUpsertHealthMetricByDate` into MortalLoom's `healthMetrics[]` array when iCloud sync is enabled (same `bloodPressureSystolic`/`bloodPressureDiastolic` keys the Swift app writes), else falls back to `data/meatspace/health-metrics.json`. New endpoints: `GET /api/meatspace/blood-pressure`, `POST /api/meatspace/blood-pressure`. Apple Health XML ingest now maps `HKQuantityTypeIdentifierBloodPressureSystolic`/`Diastolic` → `blood_pressure_systolic`/`diastolic`, and those metrics are registered in the Core Vitals section of the Health tab so exported HK data shows trend lines there too. BP classification (normal / elevated / stage-1 / stage-2 / crisis) is ported from `CardioFitnessEngine.classifyBP` into `client/src/components/meatspace/bpClassification.js` so both sides report identical categories for the same reading.
- **Hide voice widget per-browser** — the floating voice widget can now be dismissed entirely by clicking the new eye-off icon (next to the mobile FAB or in the desktop controls bar). The preference persists in `localStorage` under `portos.voice.hidden`, so iPhones/Safari sessions where the mic APIs don't work can stay clean while the desktop keeps the widget. Re-enable via **Settings → Voice → "Show floating voice widget"**; a custom `portos:voice:visibility` DOM event syncs the change live without a reload.
- **Daily Log — voice-dictatable diary in the Brain section** — new `Brain → Daily Log` tab at `/brain/daily-log` for free-form typed or dictated daily entries. One entry per date, stored in `data/brain/journals.json` with per-segment source metadata (`text` vs `voice`). Five voice tools land in the CoS: `daily_log_open` ("open my daily log" — navigates + optionally starts dictation), `daily_log_start_dictation` / `daily_log_stop_dictation`, `daily_log_append` (one-shot append without dictation mode), and `daily_log_read` (reads the entry verbatim via TTS). Dictation mode short-circuits the LLM at the server — every voice utterance appends straight to the log until the user says "stop dictation" — so the CoS stops talking back while you ramble. Tools can now emit client-side side effects (`voice:navigate`, `voice:dictation`); the Voice widget listens and routes the browser + surfaces a "Dictating to Daily Log" chip. Optional Obsidian mirror: each entry auto-writes to `<vault>/<folder>/<YYYY-MM-DD>.md` when a vault is configured in the tab's settings panel (reuses the existing Notes vault registry), picking up iCloud backup for free. Entries flow through `brainMemoryBridge.js` (new `journals` brain type, `daily-log` category) so the CoS memory system vector-embeds each day and agents can semantically search across the log history. New routes: `GET/PUT/DELETE /api/brain/daily-log/:date`, `POST /api/brain/daily-log/:date/append`, `GET/PUT /api/brain/daily-log/settings`, `POST /api/brain/daily-log/sync-obsidian`.
- **Voice CoS tool expansion — round two** — nine more hands-free tools registered in `server/services/voice/tools.js`, further expanding the Voice CoS toolset:
diff --git a/client/src/components/meatspace/BloodPressureCard.jsx b/client/src/components/meatspace/BloodPressureCard.jsx
new file mode 100644
index 0000000000..f5f45603eb
--- /dev/null
+++ b/client/src/components/meatspace/BloodPressureCard.jsx
@@ -0,0 +1,208 @@
+import { useState, useEffect, useCallback } from 'react';
+import {
+ LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend, ReferenceLine
+} from 'recharts';
+import { HeartPulse, Plus, X, Check, TrendingUp, TrendingDown } from 'lucide-react';
+import * as api from '../../services/api';
+import BrailleSpinner from '../BrailleSpinner';
+import { classifyBP, bpLongevityImpact, BP_CATEGORIES } from './bpClassification';
+
+const EMPTY_FORM = { date: '', systolic: '', diastolic: '' };
+
+function parseNum(v) {
+ if (v === '' || v == null) return null;
+ const n = parseFloat(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+export default function BloodPressureCard() {
+ const [readings, setReadings] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [showForm, setShowForm] = useState(false);
+ const [form, setForm] = useState(EMPTY_FORM);
+ const [saving, setSaving] = useState(false);
+
+ const fetchData = useCallback(async () => {
+ const data = await api.getBloodPressure().catch(() => ({ readings: [] }));
+ setReadings(data?.readings || []);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { fetchData(); }, [fetchData]);
+
+ const openForm = () => {
+ setForm({ ...EMPTY_FORM, date: new Date().toISOString().split('T')[0] });
+ setShowForm(true);
+ };
+
+ const handleSave = async () => {
+ const sys = parseNum(form.systolic);
+ const dia = parseNum(form.diastolic);
+ if (sys == null || dia == null || !form.date) return;
+ setSaving(true);
+ const reading = await api.addBloodPressure({ date: form.date, systolic: sys, diastolic: dia })
+ .catch(() => null);
+ setSaving(false);
+ if (!reading) return;
+ setReadings(prev => {
+ const others = prev.filter(r => r.date !== reading.date);
+ return [...others, reading].sort((a, b) => a.date.localeCompare(b.date));
+ });
+ setForm(EMPTY_FORM);
+ setShowForm(false);
+ };
+
+ const chartData = readings.map(r => ({
+ date: r.date,
+ label: `${new Date(r.date).getMonth() + 1}/${new Date(r.date).getDate()}`,
+ systolic: r.systolic,
+ diastolic: r.diastolic
+ }));
+
+ const latest = readings.at(-1);
+ const latestCategory = latest ? BP_CATEGORIES[classifyBP(latest.systolic, latest.diastolic)] : null;
+ const impact = latest ? bpLongevityImpact(latest.systolic, latest.diastolic) : null;
+
+ const CustomTooltip = ({ active, payload, label }) => {
+ if (!active || !payload?.length) return null;
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-2 text-sm">
+ <p className="text-gray-400 mb-1">{label}</p>
+ {payload.map(p => (
+ <p key={p.dataKey} style={{ color: p.color }}>
+ {p.name}: {p.value} mmHg
+ </p>
+ ))}
+ </div>
+ );
+ };
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-6">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <HeartPulse size={18} className="text-port-error" />
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">
+ Blood Pressure ({loading ? '...' : readings.length})
+ </h3>
+ </div>
+ {!showForm && (
+ <button
+ onClick={openForm}
+ className="flex items-center gap-1 text-xs text-port-accent hover:text-blue-300 transition-colors"
+ >
+ <Plus size={14} /> Add Reading
+ </button>
+ )}
+ </div>
+
+ {showForm && (
+ <div className="bg-port-bg border border-port-border rounded-lg p-4 mb-4">
+ <div className="grid grid-cols-3 gap-3 mb-3">
+ <div>
+ <label htmlFor="bp-date" className="text-xs text-gray-500">Date</label>
+ <input
+ id="bp-date" type="date" value={form.date}
+ onChange={e => setForm(f => ({ ...f, date: e.target.value }))}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200 font-mono"
+ />
+ </div>
+ <div>
+ <label htmlFor="bp-sys" className="text-xs text-gray-500">Systolic</label>
+ <input
+ id="bp-sys" type="number" inputMode="numeric" placeholder="120"
+ value={form.systolic}
+ onChange={e => setForm(f => ({ ...f, systolic: e.target.value }))}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200 font-mono"
+ />
+ </div>
+ <div>
+ <label htmlFor="bp-dia" className="text-xs text-gray-500">Diastolic</label>
+ <input
+ id="bp-dia" type="number" inputMode="numeric" placeholder="80"
+ value={form.diastolic}
+ onChange={e => setForm(f => ({ ...f, diastolic: e.target.value }))}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200 font-mono"
+ />
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={handleSave}
+ disabled={saving || !form.date || parseNum(form.systolic) == null || parseNum(form.diastolic) == null}
+ className="flex items-center gap-1 px-3 py-1 bg-port-accent/20 text-port-accent rounded text-sm hover:bg-port-accent/30 disabled:opacity-40"
+ >
+ <Check size={14} /> {saving ? 'Saving…' : 'Save Reading'}
+ </button>
+ <button
+ onClick={() => { setShowForm(false); setForm(EMPTY_FORM); }}
+ className="flex items-center gap-1 px-3 py-1 text-gray-400 hover:text-gray-200 text-sm"
+ >
+ <X size={14} /> Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {loading ? (
+ <div className="flex justify-center py-8"><BrailleSpinner text="Loading blood pressure" /></div>
+ ) : readings.length === 0 ? (
+ <p className="text-gray-500 text-sm">
+ No blood pressure data yet. Add a manual reading, or enable MortalLoom iCloud sync to share readings with the mobile app.
+ </p>
+ ) : (
+ <>
+ <ResponsiveContainer width="100%" height={260}>
+ <LineChart data={chartData} margin={{ top: 5, right: 5, bottom: 5, left: 0 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />
+ <XAxis
+ dataKey="label"
+ tick={{ fill: '#6b7280', fontSize: 11 }}
+ interval={Math.max(0, Math.floor(chartData.length / 12))}
+ />
+ <YAxis
+ tick={{ fill: '#6b7280', fontSize: 11 }}
+ domain={[dataMin => Math.max(40, Math.floor(dataMin - 10)), dataMax => Math.ceil(dataMax + 10)]}
+ label={{ value: 'mmHg', angle: -90, position: 'insideLeft', fill: '#6b7280', fontSize: 11 }}
+ />
+ <Tooltip content={<CustomTooltip />} />
+ <Legend />
+ <ReferenceLine y={120} stroke="#f59e0b" strokeDasharray="3 3" label={{ value: 'Elevated', fill: '#f59e0b', fontSize: 10, position: 'right' }} />
+ <ReferenceLine y={130} stroke="#f97316" strokeDasharray="3 3" label={{ value: 'Stage 1', fill: '#f97316', fontSize: 10, position: 'right' }} />
+ <ReferenceLine y={140} stroke="#ef4444" strokeDasharray="3 3" label={{ value: 'Stage 2', fill: '#ef4444', fontSize: 10, position: 'right' }} />
+ <Line type="monotone" dataKey="systolic" name="Systolic" stroke="#ef4444" dot={chartData.length <= 90} strokeWidth={2} connectNulls />
+ <Line type="monotone" dataKey="diastolic" name="Diastolic" stroke="#3b82f6" dot={chartData.length <= 90} strokeWidth={2} connectNulls />
+ </LineChart>
+ </ResponsiveContainer>
+
+ {latest && latestCategory && (
+ <div className="mt-4 pt-4 border-t border-port-border">
+ <div className="flex items-baseline justify-between flex-wrap gap-2">
+ <div>
+ <span className="text-xs text-gray-500 uppercase tracking-wider">Latest</span>
+ <div className="flex items-baseline gap-2">
+ <span className="text-2xl font-bold text-white font-mono">
+ {Math.round(latest.systolic)}/{Math.round(latest.diastolic)}
+ </span>
+ <span className="text-xs text-gray-500">mmHg · {latest.date}</span>
+ </div>
+ </div>
+ <span className={`text-sm font-semibold ${latestCategory.color}`}>
+ {latestCategory.label}
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5 mt-2 text-xs text-gray-400">
+ {impact >= 0
+ ? <TrendingUp size={12} className="text-port-success" />
+ : <TrendingDown size={12} className="text-port-error" />}
+ <span>
+ {impact >= 0 ? '+' : ''}{impact.toFixed(1)} years estimated life expectancy impact
+ </span>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/bpClassification.js b/client/src/components/meatspace/bpClassification.js
new file mode 100644
index 0000000000..aaa1ac9dde
--- /dev/null
+++ b/client/src/components/meatspace/bpClassification.js
@@ -0,0 +1,25 @@
+/**
+ * AHA/ACC 2017 hypertension classification and longevity impact.
+ * Ported from MortalLoom's CardioFitnessEngine so PortOS and the iOS/macOS
+ * companion app report identical categories for the same reading.
+ */
+
+export const BP_CATEGORIES = {
+ normal: { label: 'Normal', color: 'text-port-success', impactYears: 1.5 },
+ elevated: { label: 'Elevated', color: 'text-port-warning', impactYears: 0.0 },
+ highStage1: { label: 'High – Stage 1', color: 'text-orange-400', impactYears: -1.5 },
+ highStage2: { label: 'High – Stage 2', color: 'text-port-error', impactYears: -3.0 },
+ crisis: { label: 'Hypertensive Crisis', color: 'text-port-error', impactYears: -5.0 }
+};
+
+export function classifyBP(systolic, diastolic) {
+ if (systolic > 180 || diastolic > 120) return 'crisis';
+ if (systolic >= 140 || diastolic >= 90) return 'highStage2';
+ if (systolic >= 130 || diastolic >= 80) return 'highStage1';
+ if (systolic >= 120) return 'elevated';
+ return 'normal';
+}
+
+export function bpLongevityImpact(systolic, diastolic) {
+ return BP_CATEGORIES[classifyBP(systolic, diastolic)].impactYears;
+}
diff --git a/client/src/components/meatspace/healthMetrics.js b/client/src/components/meatspace/healthMetrics.js
index a8aea0f13f..7cc848be6d 100644
--- a/client/src/components/meatspace/healthMetrics.js
+++ b/client/src/components/meatspace/healthMetrics.js
@@ -24,6 +24,8 @@ export const METRIC_CATEGORIES = [
{ key: 'blood_oxygen_saturation', label: 'Blood Oxygen', unit: '%', color: '#3b82f6', aggregation: 'avg', formatValue: v => v.toFixed(1) },
{ key: 'respiratory_rate', label: 'Respiratory Rate', unit: 'breaths/min', color: '#06b6d4', aggregation: 'avg', formatValue: v => v.toFixed(1) },
{ key: 'vo2_max', label: 'VO2 Max', unit: 'mL/min/kg', color: '#8b5cf6', aggregation: 'avg', formatValue: v => v.toFixed(1) },
+ { key: 'blood_pressure_systolic', label: 'BP Systolic', unit: 'mmHg', color: '#ef4444', aggregation: 'avg', formatValue: v => Math.round(v).toString() },
+ { key: 'blood_pressure_diastolic', label: 'BP Diastolic', unit: 'mmHg', color: '#3b82f6', aggregation: 'avg', formatValue: v => Math.round(v).toString() },
]
},
{
diff --git a/client/src/components/meatspace/tabs/BodyTab.jsx b/client/src/components/meatspace/tabs/BodyTab.jsx
index d6e092c7ba..04a3cd6253 100644
--- a/client/src/components/meatspace/tabs/BodyTab.jsx
+++ b/client/src/components/meatspace/tabs/BodyTab.jsx
@@ -3,6 +3,7 @@ import { Scale, Eye, Plus, Pencil, Trash2, Check, X } from 'lucide-react';
import * as api from '../../../services/api';
import BrailleSpinner from '../../BrailleSpinner';
import BodyCompChart from '../BodyCompChart';
+import BloodPressureCard from '../BloodPressureCard';
const EMPTY_EYE_FORM = {
date: '', leftSphere: '', leftCylinder: '', leftAxis: '',
@@ -93,6 +94,9 @@ export default function BodyTab() {
<BodyCompChart />
</div>
+ {/* Blood Pressure */}
+ <BloodPressureCard />
+
{/* Eye Prescriptions */}
<div>
<div className="flex items-center justify-between mb-3">
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index b7e3d5ceb2..efa3a280b4 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -138,6 +138,11 @@ export const addBodyEntry = (data) => request('/meatspace/body', {
method: 'POST',
body: JSON.stringify(data)
});
+export const getBloodPressure = () => request('/meatspace/blood-pressure');
+export const addBloodPressure = (data) => request('/meatspace/blood-pressure', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
export const getEpigeneticTests = () => request('/meatspace/epigenetic');
export const addEpigeneticTest = (data) => request('/meatspace/epigenetic', {
method: 'POST',
diff --git a/server/lib/meatspaceValidation.js b/server/lib/meatspaceValidation.js
index 48f6b21123..30bd764900 100644
--- a/server/lib/meatspaceValidation.js
+++ b/server/lib/meatspaceValidation.js
@@ -139,6 +139,16 @@ export const bodyEntrySchema = z.object({
temperature: z.number().nullable().optional()
});
+// =============================================================================
+// BLOOD PRESSURE
+// =============================================================================
+
+export const bloodPressureSchema = z.object({
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
+ systolic: z.number().min(40).max(300),
+ diastolic: z.number().min(20).max(200)
+});
+
// =============================================================================
// EPIGENETIC TESTS
// =============================================================================
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index e925efad46..868399d081 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -17,6 +17,7 @@ import {
customNicotineProductUpdateSchema,
bloodTestSchema,
bodyEntrySchema,
+ bloodPressureSchema,
epigeneticTestSchema,
eyeExamSchema,
eyeExamUpdateSchema,
@@ -432,6 +433,25 @@ router.post('/body', asyncHandler(async (req, res) => {
res.status(201).json(entry);
}));
+/**
+ * GET /api/meatspace/blood-pressure
+ * Blood pressure history (merged from MortalLoom healthMetrics or local fallback)
+ */
+router.get('/blood-pressure', asyncHandler(async (req, res) => {
+ const readings = await healthService.getBloodPressureHistory();
+ res.json({ readings });
+}));
+
+/**
+ * POST /api/meatspace/blood-pressure
+ * Log a blood pressure reading (upserted by date)
+ */
+router.post('/blood-pressure', asyncHandler(async (req, res) => {
+ const data = validateRequest(bloodPressureSchema, req.body);
+ const reading = await healthService.addBloodPressureReading(data);
+ res.status(201).json(reading);
+}));
+
/**
* GET /api/meatspace/epigenetic
* Elysium results
diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.js
index a7b1b198fe..9afbabe05c 100644
--- a/server/services/appleHealthXml.js
+++ b/server/services/appleHealthXml.js
@@ -61,6 +61,10 @@ const XML_TO_METRIC_NAME = {
'hkquantitytypeidentifiercyclingpower': 'cycling_power',
'hkquantitytypeidentifiercyclingfunctionalthresholdpower': 'cycling_ftp',
+ // Cardiovascular
+ 'hkquantitytypeidentifierbloodpressuresystolic': 'blood_pressure_systolic',
+ 'hkquantitytypeidentifierbloodpressurediastolic': 'blood_pressure_diastolic',
+
// Body measurements
'hkquantitytypeidentifierbodymass': 'body_mass',
'hkquantitytypeidentifierbodymassindex': 'body_mass_index',
diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.js
index ec64e422f6..cfc4508593 100644
--- a/server/services/meatspaceHealth.js
+++ b/server/services/meatspaceHealth.js
@@ -14,7 +14,8 @@ import {
mlArrayIfEnabled,
mlPush,
mlPatchById,
- mlRemoveById
+ mlRemoveById,
+ mlUpsertHealthMetricByDate
} from './mortalLoomStore.js';
const MEATSPACE_DIR = PATHS.meatspace;
@@ -22,6 +23,7 @@ const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');
const BLOOD_TESTS_FILE = join(MEATSPACE_DIR, 'blood-tests.json');
const EPIGENETIC_TESTS_FILE = join(MEATSPACE_DIR, 'epigenetic-tests.json');
const EYES_FILE = join(MEATSPACE_DIR, 'eyes.json');
+const HEALTH_METRICS_FILE = join(MEATSPACE_DIR, 'health-metrics.json');
const byDate = (a, b) => (a.date || '').localeCompare(b.date || '');
@@ -177,3 +179,41 @@ export async function removeEyeExam(index) {
console.log(`👁️ Eye exam removed: ${removed.date}`);
return removed;
}
+
+// === Blood Pressure ===
+// Matches MortalLoom's HealthMetricEntry.bloodPressureSystolic/Diastolic (mmHg),
+// upserted by date so multiple readings on the same day (e.g. from Apple Health
+// sync + manual entry) merge into one row.
+
+export async function getBloodPressureHistory() {
+ const ml = await mlArrayIfEnabled('healthMetrics');
+ const source = ml ?? (await readJSONFile(HEALTH_METRICS_FILE, { entries: [] })).entries;
+ return source
+ .filter(m => m?.bloodPressureSystolic != null && m?.bloodPressureDiastolic != null)
+ .map(m => ({
+ date: m.date,
+ systolic: m.bloodPressureSystolic,
+ diastolic: m.bloodPressureDiastolic
+ }))
+ .sort(byDate);
+}
+
+export async function addBloodPressureReading({ date, systolic, diastolic }) {
+ const targetDate = date || new Date().toISOString().split('T')[0];
+ const patch = { bloodPressureSystolic: systolic, bloodPressureDiastolic: diastolic };
+
+ if (await isMortalLoomEnabled()) {
+ await mlUpsertHealthMetricByDate(targetDate, patch);
+ console.log(`🩺 Blood pressure ${systolic}/${diastolic} logged for ${targetDate} (MortalLoom)`);
+ return { date: targetDate, systolic, diastolic };
+ }
+
+ const log = await readJSONFile(HEALTH_METRICS_FILE, { entries: [] });
+ let entry = log.entries.find(e => e.date === targetDate);
+ if (!entry) { entry = { date: targetDate }; log.entries.push(entry); }
+ Object.assign(entry, patch);
+ log.entries.sort(byDate);
+ await writeLocal(HEALTH_METRICS_FILE, log);
+ console.log(`🩺 Blood pressure ${systolic}/${diastolic} logged for ${targetDate}`);
+ return { date: targetDate, systolic, diastolic };
+}
diff --git a/server/services/meatspaceHealth.test.js b/server/services/meatspaceHealth.test.js
index 1e89532966..8b76cfb4ae 100644
--- a/server/services/meatspaceHealth.test.js
+++ b/server/services/meatspaceHealth.test.js
@@ -99,3 +99,130 @@ describe('sortByDate', () => {
expect(items[0].date).toBe('2024-12-01');
});
});
+
+// =============================================================================
+// BLOOD PRESSURE TESTS
+// =============================================================================
+
+// Pure versions of the BP logic in meatspaceHealth.js / mortalLoomStore.js,
+// copied here per project convention (see BODY HISTORY TESTS above).
+
+function extractBloodPressureHistory(healthMetrics) {
+ return healthMetrics
+ .filter(m => m?.bloodPressureSystolic != null && m?.bloodPressureDiastolic != null)
+ .map(m => ({ date: m.date, systolic: m.bloodPressureSystolic, diastolic: m.bloodPressureDiastolic }))
+ .sort((a, b) => a.date.localeCompare(b.date));
+}
+
+function upsertHealthMetricByDate(healthMetrics, date, patch) {
+ const existing = healthMetrics.find(m => m.date === date);
+ if (existing) {
+ for (const [k, v] of Object.entries(patch)) {
+ if (v !== undefined && v !== null) existing[k] = v;
+ }
+ return { metrics: healthMetrics, entry: existing };
+ }
+ const created = { date, ...patch };
+ return { metrics: [...healthMetrics, created], entry: created };
+}
+
+describe('extractBloodPressureHistory', () => {
+ it('filters entries missing either systolic or diastolic', () => {
+ const metrics = [
+ { date: '2024-01-01', bloodPressureSystolic: 118, bloodPressureDiastolic: 78 },
+ { date: '2024-01-02', bloodPressureSystolic: 125 },
+ { date: '2024-01-03', bloodPressureDiastolic: 82 },
+ { date: '2024-01-04', heartRate: 60 }
+ ];
+ const result = extractBloodPressureHistory(metrics);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({ date: '2024-01-01', systolic: 118, diastolic: 78 });
+ });
+
+ it('sorts ascending by date', () => {
+ const metrics = [
+ { date: '2024-03-01', bloodPressureSystolic: 130, bloodPressureDiastolic: 85 },
+ { date: '2024-01-01', bloodPressureSystolic: 120, bloodPressureDiastolic: 80 },
+ { date: '2024-02-01', bloodPressureSystolic: 125, bloodPressureDiastolic: 82 }
+ ];
+ const result = extractBloodPressureHistory(metrics);
+ expect(result.map(r => r.date)).toEqual(['2024-01-01', '2024-02-01', '2024-03-01']);
+ });
+});
+
+describe('upsertHealthMetricByDate', () => {
+ it('appends a new entry when the date is unseen', () => {
+ const { metrics, entry } = upsertHealthMetricByDate(
+ [{ date: '2024-01-01', heartRate: 60 }],
+ '2024-02-01',
+ { bloodPressureSystolic: 120, bloodPressureDiastolic: 80 }
+ );
+ expect(metrics).toHaveLength(2);
+ expect(entry).toMatchObject({ date: '2024-02-01', bloodPressureSystolic: 120, bloodPressureDiastolic: 80 });
+ });
+
+ it('merges new BP fields into the existing entry for the same date', () => {
+ const metrics = [{ date: '2024-01-01', heartRate: 62, hrv: 50 }];
+ const { metrics: next, entry } = upsertHealthMetricByDate(
+ metrics,
+ '2024-01-01',
+ { bloodPressureSystolic: 118, bloodPressureDiastolic: 78 }
+ );
+ expect(next).toHaveLength(1);
+ expect(entry).toMatchObject({
+ date: '2024-01-01', heartRate: 62, hrv: 50,
+ bloodPressureSystolic: 118, bloodPressureDiastolic: 78
+ });
+ });
+
+ it('overwrites the BP fields on a repeat reading for the same date', () => {
+ const metrics = [{ date: '2024-01-01', bloodPressureSystolic: 140, bloodPressureDiastolic: 90 }];
+ const { entry } = upsertHealthMetricByDate(
+ metrics,
+ '2024-01-01',
+ { bloodPressureSystolic: 122, bloodPressureDiastolic: 81 }
+ );
+ expect(entry.bloodPressureSystolic).toBe(122);
+ expect(entry.bloodPressureDiastolic).toBe(81);
+ });
+
+ it('ignores null/undefined patch fields so partial updates do not wipe data', () => {
+ const metrics = [{ date: '2024-01-01', bloodPressureSystolic: 120, bloodPressureDiastolic: 80 }];
+ const { entry } = upsertHealthMetricByDate(
+ metrics,
+ '2024-01-01',
+ { bloodPressureSystolic: 125, bloodPressureDiastolic: null }
+ );
+ expect(entry.bloodPressureSystolic).toBe(125);
+ expect(entry.bloodPressureDiastolic).toBe(80);
+ });
+});
+
+// =============================================================================
+// BP CLASSIFICATION TESTS (AHA/ACC 2017, ported from MortalLoom CardioFitnessEngine)
+// =============================================================================
+
+function classifyBP(systolic, diastolic) {
+ if (systolic > 180 || diastolic > 120) return 'crisis';
+ if (systolic >= 140 || diastolic >= 90) return 'highStage2';
+ if (systolic >= 130 || diastolic >= 80) return 'highStage1';
+ if (systolic >= 120) return 'elevated';
+ return 'normal';
+}
+
+describe('classifyBP', () => {
+ it.each([
+ [110, 70, 'normal'],
+ [119, 79, 'normal'],
+ [120, 79, 'elevated'],
+ [125, 75, 'elevated'],
+ [130, 75, 'highStage1'],
+ [115, 82, 'highStage1'],
+ [140, 85, 'highStage2'],
+ [135, 92, 'highStage2'],
+ [185, 95, 'crisis'],
+ [150, 125, 'crisis']
+ ])('classifies %d/%d as %s', (sys, dia, expected) => {
+ expect(classifyBP(sys, dia)).toBe(expected);
+ });
+});
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index 676402aa39..fdac24ea17 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -97,6 +97,26 @@ export async function mlReplace(key, array) {
await updateStore(store => { store[key] = array; });
}
+/**
+ * Upsert a HealthMetricEntry by date — merges non-null fields into the
+ * existing entry for that date, or appends a new one. Mirrors Swift's
+ * DataStore.upsertHealthMetric + HealthMetricEntry.mergeFields.
+ */
+export async function mlUpsertHealthMetricByDate(date, patch) {
+ return updateStore(store => {
+ const existing = store.healthMetrics.find(m => m.date === date);
+ if (existing) {
+ for (const [k, v] of Object.entries(patch)) {
+ if (v !== undefined && v !== null) existing[k] = v;
+ }
+ return existing;
+ }
+ const created = { id: newMortalLoomId(), date, ...patch };
+ store.healthMetrics.push(created);
+ return created;
+ });
+}
+
/**
* Alcohol/nicotine use (date, positional-index) addressing in the PortOS daily-log.
* Return the id of the N-th record in store[key] with the given date (in stored order).