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: sync Goals + Meatspace with MortalLoom iOS/macOS app via iCloud
Adam Eivy1f972c7214fb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0beb4ceba4..ec29b3024c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,3 +1,8 @@+## Added++- **MortalLoom iCloud sync** — new Settings tab (Settings → MortalLoom) lets PortOS share Goals and Meatspace data with the MortalLoom iOS/macOS app by reading from and writing to the app's iCloud ubiquity container (`~/Library/Mobile Documents/iCloud~net~shadowpuppet~MeatSpaceTracker/Documents/MortalLoom.json`). When enabled, PortOS treats the iCloud file as the source of truth for alcohol drinks, nicotine entries, blood tests, body composition, epigenetic tests, eye exams, and goals — and every add/update/remove flow mirrors back to it so edits on either side stay in sync. Non-destructive one-shot "Import from MortalLoom" button for adopting the iCloud data into local PortOS stores by id-dedup. New `server/services/mortalLoomStore.js` exposes tight primitives (`readStore`, `updateStore`, `mlPush/mlPatchById/mlRemoveById/mlReplace`, `mlArrayIfEnabled`, `mlIdAtDateIndex`) used by `meatspaceHealth`, `meatspaceAlcohol`, `meatspaceNicotine`, and `identity`.+- **MortalLoom promo banner on Meatspace + Goals pages** — dismissible banner (stored in `localStorage` as `mortalloom-banner-dismissed-v1`) linking to the App Store (`id6760883701`) and to the new Settings tab for iCloud sync configuration.+## Fixed- **POST drill scoring paired every answer to the first prompt** — `llmResponseSchema` in `postValidation.js` didn't list `questionIndex`, so Zod's default strip mode dropped the field on its way to the scorer. The scorer's `r.questionIndex ?? i` fallback then resolved to the response-array index — always 0 for the single-response submits the trainer makes — and every answer was evaluated against the FIRST prompt of the drill. Affected bridge-word, idiom-twist, double-meaning, and every other LLM-scored POST drill (the v1.43.0 client-side fix wired up `questionIndex` on the request but it never reached the scorer). Schema now declares `questionIndex` and a regression test in `postValidation.test.js` covers the round-trip.diff --git a/.gitignore b/.gitignoreindex 20dc04f414..697810675a 100644--- a/.gitignore+++ b/.gitignore@@ -40,6 +40,7 @@ Thumbs.db# Claude worktrees.claude/worktrees/.claude/settings.local.json+.claude/scheduled_tasks.lock# BTW messages (ephemeral agent context, cleaned up after ingestion)BTW.mddiff --git a/client/src/components/MortalLoomBanner.jsx b/client/src/components/MortalLoomBanner.jsxnew file mode 100644index 0000000000..4100c9e26f--- /dev/null+++ b/client/src/components/MortalLoomBanner.jsx@@ -0,0 +1,62 @@+import { useState, useEffect } from 'react';+import { Link } from 'react-router-dom';+import { X, ExternalLink, Smartphone } from 'lucide-react';++const APP_STORE_URL = 'https://apps.apple.com/app/id6760883701';+const DISMISS_KEY = 'mortalloom-banner-dismissed-v1';++export default function MortalLoomBanner({ section = 'this data' }) {+ const [dismissed, setDismissed] = useState(true);++ useEffect(() => {+ const v = typeof window !== 'undefined' ? window.localStorage.getItem(DISMISS_KEY) : '1';+ setDismissed(v === '1');+ }, []);++ const handleDismiss = () => {+ window.localStorage.setItem(DISMISS_KEY, '1');+ setDismissed(true);+ };++ if (dismissed) return null;++ return (+ <div className="mx-4 sm:mx-6 mt-3 mb-1 rounded-xl border border-port-accent/30 bg-gradient-to-r from-port-accent/10 to-port-accent/5 px-4 py-3 flex items-start gap-3">+ <div className="shrink-0 w-8 h-8 rounded-lg bg-port-accent/20 flex items-center justify-center">+ <Smartphone size={16} className="text-port-accent" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-sm text-white font-medium">+ {section} is now available in the MortalLoom app+ </p>+ <p className="text-xs text-gray-400 mt-0.5">+ Manage your longevity data natively on iPhone, iPad, and Mac — synced privately via iCloud.+ </p>+ <div className="flex items-center gap-3 mt-2">+ <a+ href={APP_STORE_URL}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 text-xs px-3 py-1 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 transition-colors"+ >+ Install on App Store+ <ExternalLink size={10} />+ </a>+ <Link+ to="/settings/mortalloom"+ className="text-xs text-gray-400 hover:text-white transition-colors"+ >+ Configure iCloud sync →+ </Link>+ </div>+ </div>+ <button+ onClick={handleDismiss}+ className="shrink-0 text-gray-500 hover:text-white transition-colors"+ aria-label="Dismiss"+ >+ <X size={16} />+ </button>+ </div>+ );+}diff --git a/client/src/components/settings/MortalLoomTab.jsx b/client/src/components/settings/MortalLoomTab.jsxnew file mode 100644index 0000000000..bb2a90ccc1--- /dev/null+++ b/client/src/components/settings/MortalLoomTab.jsx@@ -0,0 +1,201 @@+import { useState, useEffect } from 'react';+import { Save, Download, ExternalLink, CheckCircle2, AlertCircle } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import {+ getSettings,+ updateSettings,+ getMortalLoomStatus,+ importMortalLoom+} from '../../services/api';++function formatBytes(n) {+ if (!n) return '0 B';+ const units = ['B', 'KB', 'MB', 'GB'];+ let i = 0;+ let v = n;+ while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }+ return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;+}++export function MortalLoomTab() {+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [importing, setImporting] = useState(false);+ const [enabled, setEnabled] = useState(false);+ const [path, setPath] = useState('');+ const [status, setStatus] = useState(null);+ const [lastImport, setLastImport] = useState(null);++ const refreshStatus = async () => {+ const s = await getMortalLoomStatus().catch(() => null);+ if (s) setStatus(s);+ };++ useEffect(() => {+ Promise.all([getSettings().catch(() => ({})), getMortalLoomStatus().catch(() => null)])+ .then(([settings, s]) => {+ const ml = settings?.mortalloom || {};+ setEnabled(Boolean(ml.enabled));+ setPath(ml.path || '');+ setLastImport(ml.lastImportAt || null);+ if (s) setStatus(s);+ })+ .finally(() => setLoading(false));+ }, []);++ const handleSave = async () => {+ setSaving(true);+ await updateSettings({+ mortalloom: {+ enabled,+ path: path.trim(),+ lastImportAt: lastImport+ }+ })+ .then(() => {+ toast.success('MortalLoom settings saved');+ return refreshStatus();+ })+ .catch(() => toast.error('Failed to save settings'))+ .finally(() => setSaving(false));+ };++ const handleImport = async () => {+ if (!status?.exists) {+ toast.error('MortalLoom.json not found at configured path');+ return;+ }+ setImporting(true);+ const res = await importMortalLoom().catch(() => null);+ setImporting(false);+ if (!res?.ok) {+ toast.error('Import failed: ' + (res?.reason || 'unknown'));+ return;+ }+ const totalAdded = Object.values(res.added || {}).reduce((a, b) => a + b, 0);+ const totalSkipped = Object.values(res.skipped || {}).reduce((a, b) => a + b, 0);+ toast.success(`Imported ${totalAdded} new records (${totalSkipped} already present)`);+ const now = new Date().toISOString();+ setLastImport(now);+ await updateSettings({ mortalloom: { enabled, path: path.trim(), lastImportAt: now } }).catch(() => {});+ await refreshStatus();+ };++ if (loading) return <BrailleSpinner text="Loading MortalLoom settings" />;++ const effectivePath = path.trim() || status?.defaultPath || '';++ return (+ <div className="space-y-5">+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">+ <div>+ <h3 className="text-lg font-semibold text-white mb-1">MortalLoom iCloud Sync</h3>+ <p className="text-sm text-gray-400">+ Share Goals and Meatspace data with the MortalLoom iOS/macOS app. MortalLoom writes+ a canonical <code className="text-port-accent">MortalLoom.json</code> to its iCloud+ container — enabling this lets PortOS read from and import into the same file.+ </p>+ <a+ href="https://apps.apple.com/app/id6760883701"+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 text-sm text-port-accent hover:underline mt-2"+ >+ Get MortalLoom on the App Store <ExternalLink size={12} />+ </a>+ </div>++ <div className="flex items-center gap-3">+ <label className="text-sm text-gray-400">Enabled</label>+ <button+ onClick={() => setEnabled(!enabled)}+ className={`relative w-10 h-5 rounded-full transition-colors ${enabled ? 'bg-port-accent' : 'bg-port-border'}`}+ >+ <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${enabled ? 'translate-x-5' : ''}`} />+ </button>+ <span className="text-xs text-gray-500">+ When enabled, Goals and Meatspace views surface MortalLoom data.+ </span>+ </div>++ <div className="space-y-1">+ <label className="block text-sm text-gray-400">iCloud file path</label>+ <input+ type="text"+ value={path}+ onChange={e => setPath(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent font-mono"+ placeholder={status?.defaultPath || ''}+ />+ <p className="text-xs text-gray-500">+ Leave blank to use the auto-detected MortalLoom container.+ </p>+ </div>++ <div className="flex items-center gap-3">+ <button+ onClick={handleSave}+ disabled={saving}+ className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50"+ >+ <Save size={14} className="inline mr-1" />+ {saving ? 'Saving…' : 'Save'}+ </button>+ <button+ onClick={handleImport}+ disabled={importing || !status?.exists || !enabled}+ className="px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-white rounded-lg text-sm transition-colors disabled:opacity-50"+ title={!enabled ? 'Enable sync first' : !status?.exists ? 'MortalLoom.json not found' : 'Import into PortOS'}+ >+ <Download size={14} className="inline mr-1" />+ {importing ? 'Importing…' : 'Import from MortalLoom'}+ </button>+ </div>+ <p className="text-xs text-gray-500">+ Import is non-destructive: records already present in PortOS (matched by id) are kept+ as-is. Only missing records are added.+ </p>+ </div>++ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-3">+ <h3 className="text-sm font-semibold text-white">iCloud file status</h3>+ <div className="text-xs text-gray-400 space-y-1 font-mono">+ <div className="flex items-start gap-2">+ {status?.exists ? (+ <CheckCircle2 size={14} className="text-green-400 mt-0.5 shrink-0" />+ ) : (+ <AlertCircle size={14} className="text-yellow-400 mt-0.5 shrink-0" />+ )}+ <span className="break-all">{effectivePath || '(no path)'}</span>+ </div>+ {status?.exists ? (+ <>+ <div>Size: {formatBytes(status.size)}</div>+ <div>Modified: {status.mtime ? new Date(status.mtime).toLocaleString() : '—'}</div>+ {lastImport && <div>Last import: {new Date(lastImport).toLocaleString()}</div>}+ </>+ ) : (+ <div className="text-yellow-400">File not found. Open MortalLoom on iPhone/Mac to create it, or verify the path.</div>+ )}+ </div>+ {status?.summary && (+ <div className="grid grid-cols-2 gap-2 text-xs text-gray-300 mt-2">+ <div>Goals: <span className="text-white">{status.summary.goals}</span></div>+ <div>Alcohol drinks: <span className="text-white">{status.summary.alcoholDrinks}</span></div>+ <div>Nicotine entries: <span className="text-white">{status.summary.nicotineEntries}</span></div>+ <div>Blood tests: <span className="text-white">{status.summary.bloodTests}</span></div>+ <div>Body entries: <span className="text-white">{status.summary.bodyEntries}</span></div>+ <div>Epigenetic tests: <span className="text-white">{status.summary.epigeneticTests}</span></div>+ <div>Eye exams: <span className="text-white">{status.summary.eyeExams}</span></div>+ <div>Sauna sessions: <span className="text-white">{status.summary.saunaSessions}</span></div>+ <div>Profile: <span className="text-white">{status.summary.hasProfile ? 'yes' : 'no'}</span></div>+ <div>Genome: <span className="text-white">{status.summary.hasGenome ? 'yes' : 'no'}</span></div>+ </div>+ )}+ </div>+ </div>+ );+}++export default MortalLoomTab;diff --git a/client/src/pages/Goals.jsx b/client/src/pages/Goals.jsxindex 93cdc3eb1f..a08d4da409 100644--- a/client/src/pages/Goals.jsx+++ b/client/src/pages/Goals.jsx@@ -4,6 +4,7 @@ import { Loader2, Target, TreePine, List } from 'lucide-react';import * as api from '../services/api';import GoalsTreeView from '../components/goals/GoalsTreeView';import GoalsListView from '../components/goals/GoalsListView';+import MortalLoomBanner from '../components/MortalLoomBanner';const TABS = [{ id: 'list', label: 'List', icon: List },@@ -39,6 +40,8 @@ export default function Goals() {return (<div className="h-full flex flex-col overflow-hidden">+ <MortalLoomBanner section="Goals" />+{/* Header */}<div className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-port-border bg-port-card"><div className="flex items-center gap-2 sm:gap-3 min-w-0">diff --git a/client/src/pages/MeatSpace.jsx b/client/src/pages/MeatSpace.jsxindex 53f233a822..a028a92b13 100644--- a/client/src/pages/MeatSpace.jsx+++ b/client/src/pages/MeatSpace.jsx@@ -2,6 +2,7 @@ import { useParams, useNavigate } from 'react-router-dom';import { Skull } from 'lucide-react';import { TABS } from '../components/meatspace/constants';+import MortalLoomBanner from '../components/MortalLoomBanner';import OverviewTab from '../components/meatspace/tabs/OverviewTab';import AgeTab from '../components/meatspace/tabs/AgeTab';@@ -52,6 +53,8 @@ export default function MeatSpace() {return (<div className="flex flex-col h-full">+ <MortalLoomBanner section="Meatspace health data" />+{/* Header */}<div className="shrink-0 px-6 pt-6 pb-4 border-b border-port-border"><div className="flex items-center gap-3 mb-4">diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 2fdc552d2b..3bcf970c73 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -4,13 +4,15 @@ import { DatabaseTab } from '../components/settings/DatabaseTab';import { TelegramTab } from '../components/settings/TelegramTab';import { GeneralTab } from '../components/settings/GeneralTab';import { ImageGenTab } from '../components/settings/ImageGenTab';+import { MortalLoomTab } from '../components/settings/MortalLoomTab';const TABS = [{ id: 'general', label: 'General' },{ id: 'backup', label: 'Backup' },{ id: 'database', label: 'Database' },{ id: 'image-gen', label: 'Image Gen' },- { id: 'telegram', label: 'Telegram' }+ { id: 'telegram', label: 'Telegram' },+ { id: 'mortalloom', label: 'MortalLoom' }];export default function Settings() {@@ -29,6 +31,7 @@ export default function Settings() {case 'database': return <DatabaseTab />;case 'image-gen': return <ImageGenTab />;case 'telegram': return <TelegramTab />;+ case 'mortalloom': return <MortalLoomTab />;default: return <GeneralTab />;}};diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 86b19959d7..91844becba 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -30,6 +30,7 @@ export * from './apiBrain.js';export * from './apiNotes.js';export * from './apiDigitalTwin.js';export * from './apiMeatspace.js';+export * from './apiMortalLoom.js';export * from './apiOpenClaw.js';// Default export for simplified imports (get/post/put/delete helpers)diff --git a/client/src/services/apiMortalLoom.js b/client/src/services/apiMortalLoom.jsnew file mode 100644index 0000000000..c0ebb4750b--- /dev/null+++ b/client/src/services/apiMortalLoom.js@@ -0,0 +1,5 @@+import { request } from './apiCore.js';++export const getMortalLoomStatus = () => request('/mortalloom/status');+export const importMortalLoom = () => request('/mortalloom/import', { method: 'POST' });+export const getMortalLoomAppStoreUrl = () => request('/mortalloom/app-store');diff --git a/server/index.js b/server/index.jsindex 0ae3382992..04db66418b 100644--- a/server/index.js+++ b/server/index.js@@ -59,6 +59,7 @@ import dataSyncRoutes from './routes/dataSync.js';import identityRoutes from './routes/identity.js';import instancesRoutes from './routes/instances.js';import meatspaceRoutes from './routes/meatspace.js';+import mortallomRoutes from './routes/mortalloom.js';import reviewRoutes from './routes/review.js';import githubRoutes from './routes/github.js';import settingsRoutes from './routes/settings.js';@@ -272,6 +273,7 @@ app.use('/api/insights', insightsRoutes);app.use('/api/instances', instancesRoutes);app.use('/api/sync', dataSyncRoutes);app.use('/api/meatspace', meatspaceRoutes);+app.use('/api/mortalloom', mortallomRoutes);app.use('/api/review', reviewRoutes);app.use('/api/github', githubRoutes);app.use('/api/settings', settingsRoutes);diff --git a/server/routes/mortalloom.js b/server/routes/mortalloom.jsnew file mode 100644index 0000000000..a82a302487--- /dev/null+++ b/server/routes/mortalloom.js@@ -0,0 +1,21 @@+import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { getStatus, importToPortOS, MORTALLOOM_APP_STORE_URL } from '../services/mortalLoomStore.js';++const router = Router();++router.get('/status', asyncHandler(async (_req, res) => {+ const status = await getStatus();+ res.json(status);+}));++router.get('/app-store', (_req, res) => {+ res.json({ url: MORTALLOOM_APP_STORE_URL });+});++router.post('/import', asyncHandler(async (_req, res) => {+ const result = await importToPortOS();+ res.json(result);+}));++export default router;diff --git a/server/services/identity.js b/server/services/identity.jsindex 9da2c220bf..8feaf13b6f 100644--- a/server/services/identity.js+++ b/server/services/identity.js@@ -8,6 +8,25 @@ import { getTasteProfile } from './taste-questionnaire.js';import { getActivities } from './meatspaceCalendar.js';import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';import { goalTypeEnum } from '../lib/identityValidation.js';+import { isMortalLoomEnabled, mlArrayIfEnabled, mlReplace } from './mortalLoomStore.js';++const PORTOS_GOAL_DEFAULTS = {+ parentId: null,+ tags: [],+ linkedActivities: [],+ linkedCalendars: [],+ progress: 0,+ progressHistory: [],+ todos: [],+ targetDate: null,+ timeBlockConfig: null,+ scheduledEvents: [],+ checkIns: [],+ milestones: [],+ goalType: 'standard'+};++const normalizeGoal = g => ({ ...PORTOS_GOAL_DEFAULTS, ...g });const IDENTITY_DIR = PATHS.digitalTwin;const IDENTITY_FILE = join(IDENTITY_DIR, 'identity.json');@@ -157,13 +176,23 @@ async function ensureIdentityDir() {async function loadJSON(filePath, defaultVal) {const raw = await readFile(filePath, 'utf-8').catch(() => null);- if (!raw) return structuredClone(defaultVal);- return safeJSONParse(raw, structuredClone(defaultVal));+ const data = raw ? safeJSONParse(raw, structuredClone(defaultVal)) : structuredClone(defaultVal);+ // When MortalLoom iCloud sync is enabled, the goals array is sourced from+ // MortalLoom.json; birthDate and lifeExpectancy metadata stay in local PortOS.+ if (filePath === GOALS_FILE) {+ const mlGoals = await mlArrayIfEnabled('goals');+ if (mlGoals) data.goals = mlGoals.map(normalizeGoal);+ }+ return data;}async function saveJSON(filePath, data) {await ensureIdentityDir();await writeFile(filePath, JSON.stringify(data, null, 2));+ // Mirror goals array into MortalLoom.json so iOS/macOS app sees the change.+ if (filePath === GOALS_FILE && (await isMortalLoomEnabled()) && Array.isArray(data.goals)) {+ await mlReplace('goals', data.goals);+ }}// === Pure Functions (exported for testing) ===diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.jsindex a6283a53d4..5b735bf748 100644--- a/server/services/meatspaceAlcohol.js+++ b/server/services/meatspaceAlcohol.js@@ -8,6 +8,14 @@import { readFile, writeFile } from 'fs/promises';import { join } from 'path';import { PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';+import {+ isMortalLoomEnabled,+ readDailyLogIfEnabled,+ mlPush,+ mlPatchById,+ mlRemoveById,+ mlIdAtDateIndex+} from './mortalLoomStore.js';const MEATSPACE_DIR = PATHS.meatspace;const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');@@ -132,6 +140,8 @@ export function computeRollingAverages(entries, sex = 'male') {// === File I/O ===async function loadDailyLog() {+ const ml = await readDailyLogIfEnabled();+ if (ml) return ml;const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false });if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { entries: [], lastEntryDate: null };if (!Array.isArray(raw.entries)) raw.entries = [];@@ -186,41 +196,33 @@ export async function getDailyAlcohol(from, to) {}export async function logDrink({ name, oz, abv, count = 1, date }) {- const log = await loadDailyLog();const targetDate = date || getDateString();-const standardDrinks = computeStandardDrinks(oz * count, abv);const drink = { name: name || '', abv, oz, count };- // Find or create daily entry- let entry = log.entries.find(e => e.date === targetDate);- if (!entry) {- entry = { date: targetDate };- log.entries.push(entry);+ if (await isMortalLoomEnabled()) {+ await mlPush('alcoholDrinks', { ...drink, date: targetDate });+ averageCache = null;+ const log = await loadDailyLog();+ const entry = log.entries.find(e => e.date === targetDate);+ console.log(`🍺 Logged drink (MortalLoom): ${name || 'unnamed'} ${oz}oz @ ${abv}% (${standardDrinks} std) on ${targetDate}`);+ return { drink, standardDrinks, date: targetDate, dayTotal: entry?.alcohol?.standardDrinks || standardDrinks };}- // Initialize alcohol section- if (!entry.alcohol) {- entry.alcohol = { drinks: [], standardDrinks: 0 };- }+ const log = await loadDailyLog();+ let entry = log.entries.find(e => e.date === targetDate);+ if (!entry) { entry = { date: targetDate }; log.entries.push(entry); }+ if (!entry.alcohol) entry.alcohol = { drinks: [], standardDrinks: 0 };- // Combine with existing matching drink on same dateconst existing = entry.alcohol.drinks.find(d => d.name === drink.name && d.oz === drink.oz && d.abv === drink.abv);- if (existing) {- existing.count = (existing.count || 1) + count;- } else {- entry.alcohol.drinks.push(drink);- }+ if (existing) existing.count = (existing.count || 1) + count;+ else entry.alcohol.drinks.push(drink);recalcAlcoholTotal(entry);-- // Re-sort and update lastEntryDatelog.entries.sort((a, b) => a.date.localeCompare(b.date));- log.lastEntryDate = log.entries[log.entries.length - 1].date;-+ log.lastEntryDate = log.entries.at(-1).date;await saveDailyLog(log);- console.log(`🍺 Logged drink: ${name || 'unnamed'} ${oz}oz @ ${abv}% (${standardDrinks} std drinks) on ${targetDate}`);-+ console.log(`🍺 Logged drink: ${name || 'unnamed'} ${oz}oz @ ${abv}% (${standardDrinks} std) on ${targetDate}`);return { drink, standardDrinks, date: targetDate, dayTotal: entry.alcohol.standardDrinks };}@@ -232,6 +234,24 @@ function recalcAlcoholTotal(entry) {}export async function updateDrink(date, index, updates) {+ if (await isMortalLoomEnabled()) {+ const id = await mlIdAtDateIndex('alcoholDrinks', date, index);+ if (!id) return null;+ const patch = {};+ for (const k of ['name', 'oz', 'abv', 'count', 'date']) {+ if (updates[k] !== undefined) patch[k] = updates[k];+ }+ const updated = await mlPatchById('alcoholDrinks', id, patch);+ averageCache = null;+ const effectiveDate = updated?.date || date;+ const log = await loadDailyLog();+ const entry = log.entries.find(e => e.date === effectiveDate);+ console.log(`📝 Updated drink (MortalLoom) ${date}[${index}] → ${effectiveDate}: ${updated?.name}`);+ return { drink: { name: updated.name, oz: updated.oz, abv: updated.abv, count: updated.count },+ dayTotal: entry?.alcohol?.standardDrinks || 0,+ date: effectiveDate };+ }+const log = await loadDailyLog();const entry = log.entries.find(e => e.date === date);if (!entry?.alcohol?.drinks?.[index]) return null;@@ -281,19 +301,21 @@ export async function updateDrink(date, index, updates) {}export async function removeDrink(date, index) {+ if (await isMortalLoomEnabled()) {+ const id = await mlIdAtDateIndex('alcoholDrinks', date, index);+ if (!id) return null;+ const removed = await mlRemoveById('alcoholDrinks', id);+ averageCache = null;+ return removed;+ }+const log = await loadDailyLog();const entry = log.entries.find(e => e.date === date);if (!entry?.alcohol?.drinks?.[index]) return null;const removed = entry.alcohol.drinks.splice(index, 1)[0];-- // Remove alcohol section if empty, else recalculate total- if (entry.alcohol.drinks.length === 0) {- delete entry.alcohol;- } else {- recalcAlcoholTotal(entry);- }-+ if (entry.alcohol.drinks.length === 0) delete entry.alcohol;+ else recalcAlcoholTotal(entry);await saveDailyLog(log);return removed;}diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.jsindex 4c370d2894..ec64e422f6 100644--- a/server/services/meatspaceHealth.js+++ b/server/services/meatspaceHealth.js@@ -1,13 +1,21 @@/*** MeatSpace Health Service*- * Blood tests, body composition, epigenetic tests, eyes, and nutrition CRUD.- * Reads/writes to meatspace data files.+ * Blood tests, body composition, epigenetic tests, and eyes CRUD.+ * When MortalLoom iCloud sync is enabled, reads and writes are mirrored+ * to the shared MortalLoom.json; otherwise local PortOS data files are used.*/-import { readFile, writeFile } from 'fs/promises';+import { writeFile } from 'fs/promises';import { join } from 'path';import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import {+ isMortalLoomEnabled,+ mlArrayIfEnabled,+ mlPush,+ mlPatchById,+ mlRemoveById+} from './mortalLoomStore.js';const MEATSPACE_DIR = PATHS.meatspace;const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');@@ -15,58 +23,75 @@ 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');-async function ensureMeatspaceDir() {+const byDate = (a, b) => (a.date || '').localeCompare(b.date || '');++async function writeLocal(file, data) {await ensureDir(MEATSPACE_DIR);+ await writeFile(file, JSON.stringify(data, null, 2));}// === Blood Tests ===+// Shape reconciliation: MortalLoom nests markers under `markers`; PortOS's+// BloodTestCard iterates top-level numeric fields, so we flatten on read+// and re-nest on write.export async function getBloodTests() {- return readJSONFile(BLOOD_TESTS_FILE, { tests: [], referenceRanges: {} });+ const local = await readJSONFile(BLOOD_TESTS_FILE, { tests: [], referenceRanges: {} });+ const ml = await mlArrayIfEnabled('bloodTests');+ if (!ml) return local;+ const tests = ml+ .map(({ id, markers, ...rest }) => ({ ...rest, ...(markers || {}) }))+ .sort(byDate);+ return { tests, referenceRanges: local.referenceRanges || {} };}export async function addBloodTest(test) {+ if (await isMortalLoomEnabled()) {+ const { date, id, markers, ...flat } = test;+ const stored = await mlPush('bloodTests', { date, markers: { ...(markers || {}), ...flat } });+ return { date: stored.date, ...(stored.markers || {}) };+ }const data = await getBloodTests();data.tests.push(test);- data.tests.sort((a, b) => a.date.localeCompare(b.date));- await ensureMeatspaceDir();- await writeFile(BLOOD_TESTS_FILE, JSON.stringify(data, null, 2));+ data.tests.sort(byDate);+ await writeLocal(BLOOD_TESTS_FILE, data);console.log(`🩸 Blood test added for ${test.date}`);return test;}export async function saveBloodTests(data) {- await ensureMeatspaceDir();- await writeFile(BLOOD_TESTS_FILE, JSON.stringify(data, null, 2));+ await writeLocal(BLOOD_TESTS_FILE, data);}// === Body Composition ===export async function getBodyHistory() {+ const ml = await mlArrayIfEnabled('bodyEntries');+ if (ml) return ml.map(({ id, ...rest }) => rest).sort(byDate);const log = await readJSONFile(DAILY_LOG_FILE, { entries: [] });return (log.entries || []).filter(e => e.body && Object.keys(e.body).length > 0).map(e => ({ date: e.date, ...e.body }))- .sort((a, b) => a.date.localeCompare(b.date));+ .sort(byDate);}export async function addBodyEntry({ date, ...body }) {- const log = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null });const targetDate = date || new Date().toISOString().split('T')[0];- let entry = log.entries.find(e => e.date === targetDate);- if (!entry) {- entry = { date: targetDate };- log.entries.push(entry);+ if (await isMortalLoomEnabled()) {+ const stored = await mlPush('bodyEntries', { date: targetDate, ...body });+ console.log(`⚖️ Body entry added for ${targetDate} (MortalLoom)`);+ const { id, ...rest } = stored;+ return rest;}+ const log = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null });+ let entry = log.entries.find(e => e.date === targetDate);+ if (!entry) { entry = { date: targetDate }; log.entries.push(entry); }entry.body = { ...(entry.body || {}), ...body };-- log.entries.sort((a, b) => a.date.localeCompare(b.date));- log.lastEntryDate = log.entries[log.entries.length - 1].date;-- await ensureMeatspaceDir();- await writeFile(DAILY_LOG_FILE, JSON.stringify(log, null, 2));+ log.entries.sort(byDate);+ log.lastEntryDate = log.entries.at(-1).date;+ await writeLocal(DAILY_LOG_FILE, log);console.log(`⚖️ Body entry added for ${targetDate}`);return { date: targetDate, ...entry.body };}@@ -74,15 +99,21 @@ export async function addBodyEntry({ date, ...body }) {// === Epigenetic Tests ===export async function getEpigeneticTests() {+ const ml = await mlArrayIfEnabled('epigeneticTests');+ if (ml) return { tests: [...ml].sort(byDate) };return readJSONFile(EPIGENETIC_TESTS_FILE, { tests: [] });}export async function addEpigeneticTest(test) {+ if (await isMortalLoomEnabled()) {+ const stored = await mlPush('epigeneticTests', test);+ console.log(`🧬 Epigenetic test added for ${stored.date} (MortalLoom)`);+ return stored;+ }const data = await getEpigeneticTests();data.tests.push(test);- data.tests.sort((a, b) => a.date.localeCompare(b.date));- await ensureMeatspaceDir();- await writeFile(EPIGENETIC_TESTS_FILE, JSON.stringify(data, null, 2));+ data.tests.sort(byDate);+ await writeLocal(EPIGENETIC_TESTS_FILE, data);console.log(`🧬 Epigenetic test added for ${test.date}`);return test;}@@ -90,31 +121,42 @@ export async function addEpigeneticTest(test) {// === Eyes ===export async function getEyeExams() {+ const ml = await mlArrayIfEnabled('eyeExams');+ if (ml) return { exams: [...ml].sort(byDate) };return readJSONFile(EYES_FILE, { exams: [] });}export async function addEyeExam(exam) {+ if (await isMortalLoomEnabled()) {+ const stored = await mlPush('eyeExams', exam);+ console.log(`👁️ Eye exam added for ${stored.date} (MortalLoom)`);+ return stored;+ }const data = await getEyeExams();data.exams.push(exam);- data.exams.sort((a, b) => a.date.localeCompare(b.date));- await ensureMeatspaceDir();- await writeFile(EYES_FILE, JSON.stringify(data, null, 2));+ data.exams.sort(byDate);+ await writeLocal(EYES_FILE, data);console.log(`👁️ Eye exam added for ${exam.date}`);return exam;}+const EYE_FIELDS = ['date', 'leftSphere', 'leftCylinder', 'leftAxis', 'rightSphere', 'rightCylinder', 'rightAxis'];+export async function updateEyeExam(index, updates) {const data = await getEyeExams();if (index < 0 || index >= data.exams.length) return null;-const exam = data.exams[index];- for (const key of ['date', 'leftSphere', 'leftCylinder', 'leftAxis', 'rightSphere', 'rightCylinder', 'rightAxis']) {- if (updates[key] !== undefined) exam[key] = updates[key];+ const patch = Object.fromEntries(EYE_FIELDS.filter(k => updates[k] !== undefined).map(k => [k, updates[k]]));++ if (await isMortalLoomEnabled() && exam.id) {+ const updated = await mlPatchById('eyeExams', exam.id, patch);+ console.log(`👁️ Eye exam updated: ${updated?.date} (MortalLoom)`);+ return updated;}- data.exams.sort((a, b) => a.date.localeCompare(b.date));- await ensureMeatspaceDir();- await writeFile(EYES_FILE, JSON.stringify(data, null, 2));+ Object.assign(exam, patch);+ data.exams.sort(byDate);+ await writeLocal(EYES_FILE, data);console.log(`👁️ Eye exam updated at index ${index}: ${exam.date}`);return exam;}@@ -122,11 +164,16 @@ export async function updateEyeExam(index, updates) {export async function removeEyeExam(index) {const data = await getEyeExams();if (index < 0 || index >= data.exams.length) return null;+ const target = data.exams[index];++ if (await isMortalLoomEnabled() && target.id) {+ const removed = await mlRemoveById('eyeExams', target.id);+ console.log(`👁️ Eye exam removed: ${removed?.date} (MortalLoom)`);+ return removed;+ }const [removed] = data.exams.splice(index, 1);- await ensureMeatspaceDir();- await writeFile(EYES_FILE, JSON.stringify(data, null, 2));+ await writeLocal(EYES_FILE, data);console.log(`👁️ Eye exam removed: ${removed.date}`);return removed;}-diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.jsindex 384edbce34..f8b438d33c 100644--- a/server/services/meatspaceNicotine.js+++ b/server/services/meatspaceNicotine.js@@ -8,6 +8,14 @@import { writeFile } from 'fs/promises';import { join } from 'path';import { PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';+import {+ isMortalLoomEnabled,+ readDailyLogIfEnabled,+ mlPush,+ mlPatchById,+ mlRemoveById,+ mlIdAtDateIndex+} from './mortalLoomStore.js';const MEATSPACE_DIR = PATHS.meatspace;const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');@@ -92,6 +100,8 @@ function recalcDayTotal(entry) {// === File I/O ===async function loadDailyLog() {+ const ml = await readDailyLogIfEnabled();+ if (ml) return ml;const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false });if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { entries: [], lastEntryDate: null };if (!Array.isArray(raw.entries)) raw.entries = [];@@ -142,44 +152,55 @@ export async function getDailyNicotine(from, to) {}export async function logNicotine({ product, mgPerUnit, count = 1, date }) {- const log = await loadDailyLog();const targetDate = date || getDateString();-const totalMg = Math.round(mgPerUnit * count * 100) / 100;const item = { product: product || '', mgPerUnit, count };- // Find or create daily entry- let entry = log.entries.find(e => e.date === targetDate);- if (!entry) {- entry = { date: targetDate };- log.entries.push(entry);+ if (await isMortalLoomEnabled()) {+ await mlPush('nicotineEntries', { ...item, date: targetDate });+ averageCache = null;+ const log = await loadDailyLog();+ const entry = log.entries.find(e => e.date === targetDate);+ console.log(`🚬 Logged nicotine (MortalLoom): ${product || 'unnamed'} ${mgPerUnit}mg x${count} on ${targetDate}`);+ return { item, totalMg, date: targetDate, dayTotal: entry?.nicotine?.totalMg || totalMg };}- // Initialize nicotine section- if (!entry.nicotine) {- entry.nicotine = { items: [], totalMg: 0 };- }+ const log = await loadDailyLog();+ let entry = log.entries.find(e => e.date === targetDate);+ if (!entry) { entry = { date: targetDate }; log.entries.push(entry); }+ if (!entry.nicotine) entry.nicotine = { items: [], totalMg: 0 };- // Combine with existing matching product on same dateconst existing = entry.nicotine.items.find(i => i.product === item.product && i.mgPerUnit === item.mgPerUnit);- if (existing) {- existing.count = (existing.count || 1) + count;- } else {- entry.nicotine.items.push(item);- }+ if (existing) existing.count = (existing.count || 1) + count;+ else entry.nicotine.items.push(item);recalcDayTotal(entry);- // Re-sort and update lastEntryDatelog.entries.sort((a, b) => a.date.localeCompare(b.date));- log.lastEntryDate = log.entries[log.entries.length - 1].date;-+ log.lastEntryDate = log.entries.at(-1).date;await saveDailyLog(log);console.log(`🚬 Logged nicotine: ${product || 'unnamed'} ${mgPerUnit}mg x${count} (${totalMg}mg) on ${targetDate}`);-return { item, totalMg, date: targetDate, dayTotal: entry.nicotine.totalMg };}export async function updateNicotine(date, index, updates) {+ if (await isMortalLoomEnabled()) {+ const id = await mlIdAtDateIndex('nicotineEntries', date, index);+ if (!id) return null;+ const patch = {};+ for (const k of ['product', 'mgPerUnit', 'count', 'date']) {+ if (updates[k] !== undefined) patch[k] = updates[k];+ }+ const updated = await mlPatchById('nicotineEntries', id, patch);+ averageCache = null;+ const effectiveDate = updated?.date || date;+ const log = await loadDailyLog();+ const entry = log.entries.find(e => e.date === effectiveDate);+ console.log(`📝 Updated nicotine (MortalLoom) ${date}[${index}] → ${effectiveDate}: ${updated?.product}`);+ return { item: { product: updated.product, mgPerUnit: updated.mgPerUnit, count: updated.count },+ dayTotal: entry?.nicotine?.totalMg || 0,+ date: effectiveDate };+ }+const log = await loadDailyLog();const entry = log.entries.find(e => e.date === date);if (!entry?.nicotine?.items?.[index]) return null;@@ -228,19 +249,21 @@ export async function updateNicotine(date, index, updates) {}export async function removeNicotine(date, index) {+ if (await isMortalLoomEnabled()) {+ const id = await mlIdAtDateIndex('nicotineEntries', date, index);+ if (!id) return null;+ const removed = await mlRemoveById('nicotineEntries', id);+ averageCache = null;+ return removed;+ }+const log = await loadDailyLog();const entry = log.entries.find(e => e.date === date);if (!entry?.nicotine?.items?.[index]) return null;const removed = entry.nicotine.items.splice(index, 1)[0];-- // Remove nicotine section if empty, else recalculate total- if (entry.nicotine.items.length === 0) {- delete entry.nicotine;- } else {- recalcDayTotal(entry);- }-+ if (entry.nicotine.items.length === 0) delete entry.nicotine;+ else recalcDayTotal(entry);await saveDailyLog(log);return removed;}diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsnew file mode 100644index 0000000000..676402aa39--- /dev/null+++ b/server/services/mortalLoomStore.js@@ -0,0 +1,260 @@+/**+ * MortalLoom iCloud store adapter.+ *+ * When "Use MortalLoom iCloud" is enabled in PortOS Settings, this module is+ * the single source of truth for all shared reads and writes. Both this PortOS+ * server and the MortalLoom iOS/macOS app read/write the same MortalLoom.json+ * in the app's iCloud ubiquity container, so adding data on either side shows+ * up on the other after iCloud sync completes.+ */++import { homedir } from 'os';+import { join } from 'path';+import { readFile, writeFile, stat } from 'fs/promises';+import { existsSync } from 'fs';+import { randomUUID } from 'crypto';+import { safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';+import { getSettings } from './settings.js';++const DEFAULT_ICLOUD_PATH = join(+ homedir(),+ 'Library/Mobile Documents/iCloud~net~shadowpuppet~MeatSpaceTracker/Documents/MortalLoom.json'+);++const APP_STORE_ID = '6760883701';+export const MORTALLOOM_APP_STORE_URL = `https://apps.apple.com/app/id${APP_STORE_ID}`;++const ARRAY_KEYS = [+ 'alcoholDrinks', 'alcoholPresets', 'bloodTests', 'bodyEntries',+ 'epigeneticTests', 'eyeExams', 'goals', 'habits', 'healthMetrics',+ 'nicotineEntries', 'nicotinePresets', 'saunaPresets', 'saunaSessions'+];++export function defaultStorePath() { return DEFAULT_ICLOUD_PATH; }++// === Core I/O ===++async function resolvePath() {+ const s = await getSettings();+ return s?.mortalloom?.path?.trim() || DEFAULT_ICLOUD_PATH;+}++export async function isMortalLoomEnabled() {+ const s = await getSettings();+ return Boolean(s?.mortalloom?.enabled);+}++export async function readStore() {+ const path = await resolvePath();+ if (!existsSync(path)) return null;+ const raw = await readFile(path, 'utf-8');+ return safeJSONParse(raw, null, { context: path });+}++async function writeStore(data) {+ await writeFile(await resolvePath(), JSON.stringify(data, null, 2));+}++/** Atomic read → mutate → write. Ensures all array keys are initialized. */+export async function updateStore(mutator) {+ const store = (await readStore()) || {};+ for (const k of ARRAY_KEYS) if (!Array.isArray(store[k])) store[k] = [];+ const result = await mutator(store);+ await writeStore(store);+ return result;+}++/** Uppercase UUID v4 — matches MortalLoom's iOS/macOS id format. */+export const newMortalLoomId = () => randomUUID().toUpperCase();++// === High-level entity helpers ===++/** Push a new record (minted id if absent) onto an array key. Returns the stored record. */+export async function mlPush(key, record) {+ const stored = { id: newMortalLoomId(), ...record };+ await updateStore(store => { store[key].push(stored); });+ return stored;+}++export async function mlPatchById(key, id, updates) {+ return updateStore(store => {+ const item = store[key].find(r => r.id === id);+ if (!item) return null;+ Object.assign(item, updates);+ return item;+ });+}++export async function mlRemoveById(key, id) {+ return updateStore(store => {+ const i = store[key].findIndex(r => r.id === id);+ if (i < 0) return null;+ return store[key].splice(i, 1)[0];+ });+}++export async function mlReplace(key, array) {+ await updateStore(store => { store[key] = array; });+}++/**+ * 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).+ */+export async function mlIdAtDateIndex(key, date, index) {+ const store = await readStore();+ if (!store || !Array.isArray(store[key])) return null;+ const sameDate = store[key].filter(r => r.date === date);+ return sameDate[index]?.id ?? null;+}++// === Read-side convenience ===++/** Returns an array for `key` from the store when enabled, else null (fall through to local). */+export async function mlArrayIfEnabled(key) {+ if (!(await isMortalLoomEnabled())) return null;+ const store = await readStore();+ if (!store || !Array.isArray(store[key])) return null;+ return store[key];+}++// === Daily-log composition (alcohol + nicotine records → day-keyed log) ===++export function buildDailyLogFromMortalLoom(store) {+ const empty = { entries: [], lastEntryDate: null };+ if (!store || typeof store !== 'object') return empty;++ const byDate = new Map();+ const entryFor = d => (byDate.get(d) ?? byDate.set(d, { date: d }).get(d));++ for (const d of (store.alcoholDrinks || [])) {+ if (!d?.date) continue;+ const e = entryFor(d.date);+ if (!e.alcohol) e.alcohol = { drinks: [], standardDrinks: 0 };+ const oz = Number(d.oz) || 0, abv = Number(d.abv) || 0, count = Number(d.count) || 1;+ e.alcohol.drinks.push({ name: d.name || '', oz, abv, count });+ e.alcohol.standardDrinks = Math.round((e.alcohol.standardDrinks + (oz * count * (abv / 100)) / 0.6) * 100) / 100;+ }++ for (const n of (store.nicotineEntries || [])) {+ if (!n?.date) continue;+ const e = entryFor(n.date);+ if (!e.nicotine) e.nicotine = { items: [], totalMg: 0 };+ const mgPerUnit = Number(n.mgPerUnit) || 0, count = Number(n.count) || 1;+ e.nicotine.items.push({ product: n.product || '', mgPerUnit, count });+ e.nicotine.totalMg = Math.round((e.nicotine.totalMg + mgPerUnit * count) * 100) / 100;+ }++ const entries = [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));+ return { entries, lastEntryDate: entries.at(-1)?.date || null };+}++export async function readDailyLogIfEnabled() {+ if (!(await isMortalLoomEnabled())) return null;+ const store = await readStore();+ return store ? buildDailyLogFromMortalLoom(store) : null;+}++// === Status / import (used by Settings UI) ===++export async function getStatus() {+ const s = await getSettings();+ const path = s?.mortalloom?.path?.trim() || DEFAULT_ICLOUD_PATH;+ const enabled = Boolean(s?.mortalloom?.enabled);+ const exists = existsSync(path);+ if (!exists) {+ return { enabled, path, usingDefault: path === DEFAULT_ICLOUD_PATH, defaultPath: DEFAULT_ICLOUD_PATH,+ exists: false, size: 0, mtime: null, summary: null, appStoreUrl: MORTALLOOM_APP_STORE_URL };+ }+ const st = await stat(path);+ const data = safeJSONParse(await readFile(path, 'utf-8'), null);+ const count = k => Array.isArray(data?.[k]) ? data[k].length : 0;+ return {+ enabled, path, usingDefault: path === DEFAULT_ICLOUD_PATH, defaultPath: DEFAULT_ICLOUD_PATH,+ exists: true, size: st.size, mtime: st.mtime.toISOString(),+ summary: data && typeof data === 'object' ? {+ goals: count('goals'),+ alcoholDrinks: count('alcoholDrinks'),+ nicotineEntries: count('nicotineEntries'),+ bloodTests: count('bloodTests'),+ bodyEntries: count('bodyEntries'),+ epigeneticTests: count('epigeneticTests'),+ eyeExams: count('eyeExams'),+ saunaSessions: count('saunaSessions'),+ hasProfile: Boolean(data.profile),+ hasGenome: Boolean(data.genomeScanRecord)+ } : null,+ appStoreUrl: MORTALLOOM_APP_STORE_URL+ };+}++/** Non-destructive import: append MortalLoom records missing from PortOS local files. */+export async function importToPortOS() {+ const store = await readStore();+ if (!store) return { ok: false, reason: 'mortalloom-file-not-found' };++ const report = { added: {}, skipped: {} };+ const mergeById = async (mlArr, localPath, pathDir) => {+ const local = await readJSONFile(localPath, []);+ const localArr = Array.isArray(local) ? local : [];+ const seen = new Set(localArr.map(x => x.id).filter(Boolean));+ let added = 0, skipped = 0;+ for (const item of mlArr) {+ if (item?.id && seen.has(item.id)) { skipped++; continue; }+ localArr.push(item); added++;+ }+ if (added > 0) {+ await ensureDir(pathDir);+ await writeFile(localPath, JSON.stringify(localArr, null, 2));+ }+ return { added, skipped };+ };++ // Goals live in a wrapper object, not a bare array+ const goalsPath = dataPath('digital-twin', 'goals.json');+ const localGoals = await readJSONFile(goalsPath, { goals: [] });+ const seenGoalIds = new Set((localGoals.goals || []).map(g => g.id));+ let gAdded = 0, gSkipped = 0;+ for (const g of (store.goals || [])) {+ if (seenGoalIds.has(g.id)) { gSkipped++; continue; }+ localGoals.goals.push(g); gAdded++;+ }+ if (gAdded > 0) {+ await ensureDir(dataPath('digital-twin'));+ localGoals.updatedAt = new Date().toISOString();+ await writeFile(goalsPath, JSON.stringify(localGoals, null, 2));+ }+ report.added.goals = gAdded; report.skipped.goals = gSkipped;++ for (const [mlKey, fileName] of [+ ['alcoholDrinks', 'alcohol-drinks.json'],+ ['nicotineEntries', 'nicotine-entries.json'],+ ['bloodTests', 'blood-tests.json'],+ ['bodyEntries', 'body-entries.json'],+ ['epigeneticTests', 'epigenetic-tests.json'],+ ['eyeExams', 'eyes.json'],+ ['saunaSessions', 'sauna-sessions.json'],+ ['habits', 'habits.json'],+ ['healthMetrics', 'health-metrics.json']+ ]) {+ const mlArr = store[mlKey] || [];+ if (mlArr.length === 0) { report.added[mlKey] = 0; report.skipped[mlKey] = 0; continue; }+ const { added, skipped } = await mergeById(mlArr, dataPath('meatspace', fileName), dataPath('meatspace'));+ report.added[mlKey] = added; report.skipped[mlKey] = skipped;+ }++ if (store.profile && typeof store.profile === 'object') {+ const profilePath = dataPath('meatspace', 'profile.json');+ if (!existsSync(profilePath)) {+ await ensureDir(dataPath('meatspace'));+ await writeFile(profilePath, JSON.stringify(store.profile, null, 2));+ report.added.profile = 1; report.skipped.profile = 0;+ } else {+ report.added.profile = 0; report.skipped.profile = 1;+ }+ }++ report.ok = true;+ report.importedAt = new Date().toISOString();+ return report;+}