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
fix: refresh MeatSpace overview from persisted changes (#8554)
[._.]/ Adam Eivyecf383108069
diff --git a/client/src/components/meatspace/tabs/OverviewTab.jsx b/client/src/components/meatspace/tabs/OverviewTab.jsxindex 819c55b96a..d6d2edfef4 100644--- a/client/src/components/meatspace/tabs/OverviewTab.jsx+++ b/client/src/components/meatspace/tabs/OverviewTab.jsx@@ -1,11 +1,10 @@-import { useState, useCallback } from 'react';import { useNavigate } from 'react-router';import { Beer, Scale, HeartPulse, Dna, Eye, Dumbbell, Database, Rocket, Calendar } from 'lucide-react';import * as api from '../../../services/api';import BrailleSpinner from '../../BrailleSpinner';import DeathClockCountdown from '../../DeathClockCountdown';import ProvenanceChip from '../../ui/ProvenanceChip';-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';+import { useSocketResource } from '../../../hooks/useSocketResource';import { clickableProps, onActivateKeyDown } from '../../../lib/a11yKeyboard.js';import { formatWeight, formatPercent, formatDateShort, formatCount } from '../../../utils/formatters';@@ -148,42 +147,26 @@ function riskColor(level) {return 'text-port-error';}+const OVERVIEW_EVENTS = ['meatspace:changed'];+const fetchHealthBody = () => api.getLatestHealthMetrics(['body_mass', 'body_fat_percentage', 'lean_body_mass']);+function useOverviewResource(resource, fetchResource) {+ return useSocketResource(fetchResource, {+ events: OVERVIEW_EVENTS,+ matchesEvent: payload => payload?.resources?.includes(resource),+ });+}+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);- const [calendar, setCalendar] = useState(null);- const [loading, setLoading] = useState(true);+ const { data, loading } = useOverviewResource('overview', api.getMeatspaceOverview);+ const { data: alcohol } = useOverviewResource('alcohol', api.getAlcoholSummary);+ const { data: body } = useOverviewResource('body', api.getBodyHistory);+ const { data: healthBody } = useOverviewResource('healthBody', fetchHealthBody);+ const { data: blood } = useOverviewResource('blood', api.getBloodTests);+ const { data: epigenetic } = useOverviewResource('epigenetic', api.getEpigeneticTests);+ const { data: eyes } = useOverviewResource('eyes', api.getEyeExams);+ const { data: calendar } = useOverviewResource('calendar', api.getLifeCalendar);const navigate = useNavigate();- const fetchData = useCallback(async () => {- const [overview, alc, bod, bld, epi, eye, hBody, cal] = 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),- api.getLifeCalendar().catch(() => null),- ]);- setData(overview);- setAlcohol(alc);- setBody(bod);- setHealthBody(hBody);- setBlood(bld);- setEpigenetic(epi);- setEyes(eye);- setCalendar(cal);- setLoading(false);- }, []);-- useAutoRefetch(fetchData, 60_000, { pollOnly: true });-if (loading) {return (<div className="flex items-center justify-center h-64">diff --git a/client/src/components/meatspace/tabs/OverviewTab.test.jsx b/client/src/components/meatspace/tabs/OverviewTab.test.jsxnew file mode 100644index 0000000000..4f493944fd--- /dev/null+++ b/client/src/components/meatspace/tabs/OverviewTab.test.jsx@@ -0,0 +1,74 @@+import { act, render, screen, cleanup } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import { beforeEach, afterEach, expect, it, vi } from 'vitest';+vi.mock('../../../services/socket', async () => {+ const { EventEmitter } = await import('node:events');+ return { default: new EventEmitter() };+});+vi.mock('../../../services/api', () => ({+ getMeatspaceOverview: vi.fn(), getAlcoholSummary: vi.fn(), getBodyHistory: vi.fn(),+ getBloodTests: vi.fn(), getEpigeneticTests: vi.fn(), getEyeExams: vi.fn(),+ getLatestHealthMetrics: vi.fn(), getLifeCalendar: vi.fn(),+}));+vi.mock('../../DeathClockCountdown', () => ({ default: () => null }));+import * as api from '../../../services/api';+import socket from '../../../services/socket';+import OverviewTab from './OverviewTab';++beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ api.getMeatspaceOverview.mockResolvedValue({ summary: { totalEntries: 7 } });+ api.getAlcoholSummary.mockResolvedValue({});+ api.getBodyHistory.mockResolvedValue([{ date: '2026-01-01', weightLbs: 170 }]);+ api.getBloodTests.mockResolvedValue({ tests: [] });+ api.getEpigeneticTests.mockResolvedValue({ tests: [] });+ api.getEyeExams.mockResolvedValue({ exams: [] });+ api.getLatestHealthMetrics.mockResolvedValue({});+ api.getLifeCalendar.mockResolvedValue({});+});+afterEach(() => { cleanup(); vi.useRealTimers(); });++it('renders local and mirrored invalidations selectively, retaining good data on failed reads without polling', async () => {+ render(<MemoryRouter><OverviewTab /></MemoryRouter>);+ await act(async () => {});+ expect(screen.getByText('170 lbs')).toBeInTheDocument();+ await act(async () => { await vi.advanceTimersByTimeAsync(180_000); });+ for (const fn of Object.values(api)) expect(fn).toHaveBeenCalledTimes(1);++ api.getBodyHistory.mockResolvedValue([{ date: '2026-01-02', weightLbs: 172 }]);+ await act(async () => { socket.emit('meatspace:changed', { resources: ['body', 'overview'] }); });+ expect(screen.getByText('172 lbs')).toBeInTheDocument();+ expect(api.getAlcoholSummary).toHaveBeenCalledTimes(1);+ expect(api.getMeatspaceOverview).toHaveBeenCalledTimes(2);++ // MortalLoom and local writers share the same invalidation contract.+ api.getBloodTests.mockResolvedValue({ tests: [{ date: '2026-02-03' }] });+ await act(async () => { socket.emit('meatspace:changed', { resources: ['blood'] }); });+ expect(screen.getByText('2026-02-03')).toBeInTheDocument();+ api.getBodyHistory.mockRejectedValue(new Error('temporarily unavailable'));+ await act(async () => { socket.emit('meatspace:changed', { resources: ['body'] }); });+ expect(screen.getByText('172 lbs')).toBeInTheDocument();+});++it('reconciles each resource once on reconnect and once on tab re-show, then unsubscribes', async () => {+ const view = render(<MemoryRouter><OverviewTab /></MemoryRouter>);+ await act(async () => {});+ await act(async () => { socket.emit('connect'); });+ for (const fn of Object.values(api)) expect(fn).toHaveBeenCalledTimes(2);+ await act(async () => {+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ document.dispatchEvent(new Event('visibilitychange'));+ socket.emit('meatspace:changed', { resources: ['body'] });+ });+ for (const fn of Object.values(api)) expect(fn).toHaveBeenCalledTimes(2);+ await act(async () => {+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ document.dispatchEvent(new Event('visibilitychange'));+ document.dispatchEvent(new Event('visibilitychange'));+ });+ for (const fn of Object.values(api)) expect(fn).toHaveBeenCalledTimes(3);+ view.unmount();+ expect(socket.listenerCount('meatspace:changed')).toBe(0);+});diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 7de2d19155..f220acd78e 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -59,6 +59,12 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({summary: 'Invalidate operational goal progress after learning statistics persist.',payloadSchema: { type: 'object', properties: {}, additionalProperties: false },},+ 'meatspace:changed': {+ direction: 'server-to-client',+ summary: 'Overview resource invalidation after persisted local or mirrored health changes.',+ payloadSchema: { type: 'object', required: ['resources'], additionalProperties: false,+ properties: { resources: { type: 'array', items: { type: 'string', enum: ['overview', 'alcohol', 'body', 'healthBody', 'blood', 'epigenetic', 'eyes', 'calendar'] } } } },+ },'portos:auto-update:changed': {direction: 'server-to-client',summary: 'Invalidate updater status after runtime, configuration or external git ref changes.',diff --git a/server/services/appleHealthIngest.js b/server/services/appleHealthIngest.jsindex 344c328169..2af41715be 100644--- a/server/services/appleHealthIngest.js+++ b/server/services/appleHealthIngest.js@@ -5,6 +5,7 @@* metric+timestamp, and day-partitioned file storage at data/health/YYYY-MM-DD.json.*/+import { invalidateMeatspace } from './meatspaceEvents.js';import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { createKeyedFileWriteQueue } from '../lib/fileWriteQueue.js';@@ -67,11 +68,14 @@ export async function readDayFile(dateStr) {* @param {Object} data - Day file data to write* @returns {Promise<void>}*/-export async function writeDayFile(dateStr, data) {+export async function writeDayFile(dateStr, data, changedMetrics = Object.keys(data.metrics || {})) {await ensureDir(PATHS.health);data.updated = new Date().toISOString();const filePath = join(PATHS.health, `${dateStr}.json`);await atomicWrite(filePath, data);+ if (changedMetrics.some(name => ['body_mass', 'body_fat_percentage', 'lean_body_mass'].includes(name))) {+ invalidateMeatspace(['healthBody']);+ }}/**@@ -135,7 +139,7 @@ export async function mergeIntoDay(dateStr, metricName, newPoints) {if (added > 0 || updated > 0) {dayData.metrics[metricName] = result;- await writeDayFile(dateStr, dayData);+ await writeDayFile(dateStr, dayData, [metricName]);}return { added, updated, totalPoints: result.length };diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.jsindex b5679c4775..f92b706992 100644--- a/server/services/appleHealthXml.js+++ b/server/services/appleHealthXml.js@@ -271,7 +271,7 @@ async function flushDayBuckets(dayBuckets) {}}- await writeDayFile(dateStr, dayData);+ await writeDayFile(dateStr, dayData, Object.keys(metrics));flushedDates.add(dateStr);});diff --git a/server/services/identity/longevity.js b/server/services/identity/longevity.jsindex ba2ab7d693..9805d38660 100644--- a/server/services/identity/longevity.js+++ b/server/services/identity/longevity.js@@ -1,3 +1,4 @@+import { invalidateMeatspace } from '../meatspaceEvents.js';import { getGenomeSummary } from '../genome.js';import {GOALS_FILE,@@ -78,6 +79,7 @@ export async function deriveLongevity(birthDate) {};await saveJSON(LONGEVITY_FILE, longevity);+ invalidateMeatspace(['overview', 'calendar']);const markerCount = Object.keys(longevityMarkers).length + Object.keys(cardiovascularMarkers).length;console.log(`🧬 Longevity derived: ${lifeExpectancy.adjusted}y (${markerCount} markers, confidence: ${confidence})`);diff --git a/server/services/meatspace.js b/server/services/meatspace.jsindex fa9e0fb131..e05b3d094d 100644--- a/server/services/meatspace.js+++ b/server/services/meatspace.js@@ -5,7 +5,7 @@* and LEV 2045 tracker. Reads genome/longevity data from Digital Twin.*/-import { meatspaceEvents } from './meatspaceEvents.js';+import { meatspaceEvents, invalidateMeatspace } from './meatspaceEvents.js';import { readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile, readJSONFileStrict } from '../lib/fileUtils.js';@@ -74,6 +74,7 @@ async function saveConfig(config) {await ensureMeatspaceDir();await atomicWrite(CONFIG_FILE, config);meatspaceEvents.emit('death-clock:changed', {});+ invalidateMeatspace(['overview', 'alcohol', 'calendar']);}// === Sex Detection ===diff --git a/server/services/meatspaceCalendar.js b/server/services/meatspaceCalendar.jsindex 3cac2fd9c4..56e14a8fee 100644--- a/server/services/meatspaceCalendar.js+++ b/server/services/meatspaceCalendar.js@@ -6,6 +6,7 @@* based on birth date and life expectancy.*/+import { invalidateMeatspace } from './meatspaceEvents.js';import { readFile } from 'fs/promises';import { join } from 'path';import { randomUUID } from 'crypto';@@ -191,6 +192,7 @@ async function loadActivities() {async function saveActivities(data) {await ensureDir(MEATSPACE_DIR);await atomicWrite(ACTIVITIES_FILE, data);+ invalidateMeatspace(['calendar']);}// === Default Activities ===@@ -224,6 +226,7 @@ async function loadEvents() {async function saveEvents(data) {await ensureDir(MEATSPACE_DIR);await atomicWrite(EVENTS_FILE, data);+ invalidateMeatspace(['calendar']);}export async function getLifeEvents() {diff --git a/server/services/meatspaceDailyLog.js b/server/services/meatspaceDailyLog.jsindex 84ec834b67..209f403ddc 100644--- a/server/services/meatspaceDailyLog.js+++ b/server/services/meatspaceDailyLog.js@@ -23,6 +23,7 @@* caller that COUNTS these entries can't report a fake 0 (#2726).*/+import { invalidateMeatspace } from './meatspaceEvents.js';import { randomUUID } from 'crypto';import { join } from 'path';import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../lib/fileUtils.js';@@ -38,6 +39,9 @@ export const queueDailyLogWrite = createFileWriteQueue();// Fresh object per call — callers mutate the log they get back (entry push,// lastEntryDate stamp) before writing it, so a shared constant would leak state.const emptyDailyLog = () => ({ entries: [], lastEntryDate: null });+const resourceSnapshot = (entries, key) => JSON.stringify(+ entries?.filter(entry => entry[key]).map(entry => ({ date: entry.date, value: entry[key] }))+);/*** Read the local `daily-log.json` mirror, without consulting MortalLoom.@@ -97,6 +101,8 @@ export async function loadMeatspaceDailyLog({ strict = false, label = 'MeatSpaceexport async function mutateDailyLog(mutatorFn, { label = 'MeatSpace' } = {}) {return queueDailyLogWrite(async () => {const log = await readLocalDailyLog({ strict: true, label });+ const beforeAlcohol = resourceSnapshot(log.entries, 'alcohol');+ const beforeBody = resourceSnapshot(log.entries, 'body');const result = await mutatorFn(log);if (result === null) return result;if (Array.isArray(log?.entries)) {@@ -105,6 +111,11 @@ export async function mutateDailyLog(mutatorFn, { label = 'MeatSpace' } = {}) {}await ensureDir(PATHS.meatspace);await atomicWrite(DAILY_LOG_FILE, log);+ invalidateMeatspace([+ 'overview',+ ...(beforeAlcohol !== resourceSnapshot(log.entries, 'alcohol') ? ['alcohol'] : []),+ ...(beforeBody !== resourceSnapshot(log.entries, 'body') ? ['body'] : []),+ ]);return result !== undefined ? result : log;});}diff --git a/server/services/meatspaceDailyLog.test.js b/server/services/meatspaceDailyLog.test.jsindex a359e06f92..a6b96ec051 100644--- a/server/services/meatspaceDailyLog.test.js+++ b/server/services/meatspaceDailyLog.test.js@@ -339,3 +339,41 @@ describe('serialized daily-log writes (#8032)', () => {expect((await getNicotineSummary()).today).toBe(7);});});++it('invalidates only affected overview resources after a successful body write, never a failed write', async () => {+ const { meatspaceEvents } = await import('./meatspaceEvents.js');+ const changed = vi.fn();+ meatspaceEvents.on('changed', changed);+ try {+ readJSONFile.mockImplementation(async () => ({ entries: [] }));+ let persist;+ atomicWrite.mockImplementationOnce(() => new Promise(resolve => { persist = resolve; }));+ const writing = addBodyEntry({ date: '2024-06-01', weightLbs: 170 });+ await vi.waitFor(() => expect(persist).toBeTypeOf('function'));+ expect(changed).not.toHaveBeenCalled();+ persist();+ await writing;+ expect(changed).toHaveBeenCalledExactlyOnceWith({ resources: ['overview', 'body'] });+ changed.mockClear();+ atomicWrite.mockRejectedValueOnce(new Error('write failed'));+ await expect(addBodyEntry({ date: '2024-06-01', weightLbs: 171 })).rejects.toThrow('write failed');+ expect(changed).not.toHaveBeenCalled();+ } finally {+ meatspaceEvents.off('changed', changed);+ }+});++it('invalidates the alcohol summary cache when a mirrored drink changes', async () => {+ const { invalidateMortalLoomChanges } = await import('./meatspaceEvents.js');+ readJSONFile.mockResolvedValue({ sex: 'male' });+ readDailyLogIfEnabled.mockResolvedValue({ entries: [] });+ invalidateMortalLoomChanges(null, { alcoholDrinks: [] });+ const before = await getAlcoholSummary();+ expect(before.recentEntries).toEqual([]);+ readDailyLogIfEnabled.mockResolvedValue({ entries: [{+ date: '2024-06-01',+ alcohol: { standardDrinks: 1, drinks: [{ name: 'Example Drink', oz: 12, abv: 5 }] },+ }] });+ invalidateMortalLoomChanges({ alcoholDrinks: [] }, { alcoholDrinks: [{ id: 'example-drink' }] });+ expect((await getAlcoholSummary()).recentEntries).toHaveLength(1);+});diff --git a/server/services/meatspaceEvents.js b/server/services/meatspaceEvents.jsindex cd979a4c70..f72ba6ecbf 100644--- a/server/services/meatspaceEvents.js+++ b/server/services/meatspaceEvents.js@@ -1,4 +1,21 @@import { EventEmitter } from 'node:events';-// Invalidation only: personal inputs remain behind the normal API boundary.+// Invalidation metadata only: personal health records never travel on this bus.export const meatspaceEvents = new EventEmitter();+const COLLECTION_RESOURCES = {+ profile: ['overview', 'alcohol', 'calendar'],+ alcoholDrinks: ['alcohol'],+ bodyEntries: ['body'],+ bloodTests: ['blood'],+ epigeneticTests: ['epigenetic'],+ eyeExams: ['eyes'],+};+export function invalidateMeatspace(resources) {+ if (resources.length) meatspaceEvents.emit('changed', { resources: [...new Set(resources)] });+}+export function invalidateMortalLoomChanges(before, after) {+ const resources = Object.entries(COLLECTION_RESOURCES)+ .filter(([key]) => JSON.stringify(before?.[key]) !== JSON.stringify(after?.[key]))+ .flatMap(([, affected]) => affected);+ invalidateMeatspace(resources);+}diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.jsindex daff19d013..203a8c0a04 100644--- a/server/services/meatspaceHealth.js+++ b/server/services/meatspaceHealth.js@@ -6,6 +6,7 @@* to the shared MortalLoom.json; otherwise local PortOS data files are used.*/+import { invalidateMeatspace } from './meatspaceEvents.js';import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';import { readLocalDailyLog, mutateDailyLog } from './meatspaceDailyLog.js';@@ -30,6 +31,8 @@ const byDate = (a, b) => (a.date || '').localeCompare(b.date || '');async function writeLocal(file, data) {await ensureDir(MEATSPACE_DIR);await atomicWrite(file, data);+ const resource = { [BLOOD_TESTS_FILE]: 'blood', [EPIGENETIC_TESTS_FILE]: 'epigenetic', [EYES_FILE]: 'eyes' }[file];+ if (resource) invalidateMeatspace([resource]);}// === Blood Tests ===diff --git a/server/services/meatspaceOverviewEvents.test.js b/server/services/meatspaceOverviewEvents.test.jsnew file mode 100644index 0000000000..2d01149444--- /dev/null+++ b/server/services/meatspaceOverviewEvents.test.js@@ -0,0 +1,56 @@+import { beforeEach, afterEach, expect, it, vi } from 'vitest';++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { meatspace: '/mock/meatspace', data: '/mock', health: '/mock/health', digitalTwin: '/mock/digital-twin' },+ readJSONFile: vi.fn(async (_path, fallback) => structuredClone(fallback)),+ atomicWrite: vi.fn(), ensureDir: vi.fn(), readJSONFileStrict: vi.fn(),+ getDateString: () => '2026-01-01',+}));+vi.mock('./genome.js', () => ({ getSnpIndex: vi.fn() }));+vi.mock('./mortalLoomStore.js', () => ({+ mlGetProfileIfEnabled: vi.fn(), mlPatchProfileIfEnabled: vi.fn(),+ readDailyLogIfEnabled: vi.fn(), isMortalLoomEnabled: vi.fn(async () => false),+ mlArrayIfEnabled: vi.fn(async () => null),+}));+import { atomicWrite } from '../lib/fileUtils.js';+import { updateLifestyle } from './meatspace.js';+import { addActivity } from './meatspaceCalendar.js';+import { addBloodTest } from './meatspaceHealth.js';+import { writeDayFile } from './appleHealthIngest.js';+import { meatspaceEvents } from './meatspaceEvents.js';++const changed = vi.fn();+beforeEach(() => {+ vi.clearAllMocks();+ atomicWrite.mockResolvedValue(undefined);+ meatspaceEvents.on('changed', changed);+});+afterEach(() => meatspaceEvents.off('changed', changed));++// These are distinct persistence boundaries; an early emit at any one would+// make the event-driven overview read the old value with no later correction.+it.each([+ ['lifestyle', () => updateLifestyle({ sleepHoursPerNight: 8 }), ['overview', 'alcohol', 'calendar']],+ ['calendar', () => addActivity({ name: 'Example Activity', cadence: 'week', frequency: 1 }), ['calendar']],+ ['local health CRUD', () => addBloodTest({ date: '2026-01-01' }), ['blood']],+ ['Apple Health import', () => writeDayFile('2026-01-01', { metrics: { body_mass: [] } }), ['healthBody']],+])('%s invalidates after persistence and never on rejected persistence', async (_name, write, resources) => {+ let persist;+ atomicWrite.mockImplementationOnce(() => new Promise(resolve => { persist = resolve; }));+ const writing = write();+ await vi.waitFor(() => expect(persist).toBeTypeOf('function'));+ expect(changed).not.toHaveBeenCalled();+ persist();+ await writing;+ expect(changed).toHaveBeenCalledExactlyOnceWith({ resources });+ changed.mockClear();+ atomicWrite.mockRejectedValueOnce(new Error('write failed'));+ await expect(write()).rejects.toThrow('write failed');+ expect(changed).not.toHaveBeenCalled();+});+++it('does not refresh body metrics for unrelated Apple Health changes', async () => {+ await writeDayFile('2026-01-01', { metrics: { body_mass: [], heart_rate: [] } }, ['heart_rate']);+ expect(changed).not.toHaveBeenCalled();+});diff --git a/server/services/meatspaceSubstanceLog.js b/server/services/meatspaceSubstanceLog.jsindex dee95753e7..785c0b6d8d 100644--- a/server/services/meatspaceSubstanceLog.js+++ b/server/services/meatspaceSubstanceLog.js@@ -1,5 +1,6 @@/** Shared event-log workflow for MeatSpace substance records. */import { join } from 'path';+import { meatspaceEvents } from './meatspaceEvents.js';import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';import { loadMeatspaceDailyLog, mutateDailyLog, newDailyLogEvent, stampDailyLogEventEdit, tombstoneDailyLogEvent } from './meatspaceDailyLog.js';import { isMortalLoomEnabled, mlPush, mlPatchById, mlRemoveById, mlIdAtDateIndex } from './mortalLoomStore.js';@@ -10,7 +11,11 @@ export function createSubstanceLog({ key, itemsField, totalField, mlCollection,const itemName = key === 'alcohol' ? 'drink' : 'item';let averageCache = null;let averageCacheAt = 0;- const invalidate = () => { averageCache = null; };+ let cacheRevision = 0;+ const invalidate = () => { averageCache = null; cacheRevision += 1; };+ meatspaceEvents.on('changed', ({ resources }) => {+ if (resources.includes('alcohol')) invalidate();+ });const recalc = (entry) => {entry[key][totalField] = Math.round(entry[key][itemsField].reduce((sum, item) => sum + computeTotal(item), 0) * 100) / 100;};@@ -22,6 +27,7 @@ export function createSubstanceLog({ key, itemsField, totalField, mlCollection,async function summary() {const now = Date.now();if (averageCache && now - averageCacheAt < 5 * 60 * 1000) return averageCache;+ const revision = cacheRevision;const [log, config] = await Promise.all([loadDailyLog(), summaryConfig?.()]);const entries = log.entries || [];const averages = computeAverages(entries, config);@@ -31,9 +37,12 @@ export function createSubstanceLog({ key, itemsField, totalField, mlCollection,const weekAgoStr = getDateString(weekAgo);const recentEntries = entries.filter(e => e.date >= weekAgoStr && e.date <= today && e[key]?.[itemsField]?.length > 0).sort((a, b) => b.date.localeCompare(a.date));- averageCache = { ...averages, recentEntries };- averageCacheAt = now;- return averageCache;+ const result = { ...averages, recentEntries };+ if (revision === cacheRevision) {+ averageCache = result;+ averageCacheAt = now;+ }+ return result;}async function daily(from, to, options) {diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsindex e1da831525..dcc5255d8d 100644--- a/server/services/mortalLoomStore.js+++ b/server/services/mortalLoomStore.js@@ -12,6 +12,7 @@ import { homedir } from 'os';import { join } from 'path';import { stat } from 'fs/promises';import { existsSync } from 'fs';+import { invalidateMeatspace, invalidateMortalLoomChanges } from './meatspaceEvents.js';import { randomUUID } from 'crypto';import { atomicWrite, safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';import { ICLOUD_NOT_MATERIALIZED, isEvictedStats, materializeAndWait, readIfMaterialized, requestMaterialization } from '../lib/icloudFile.js';@@ -204,7 +205,51 @@ async function materializeNow(path) {let listenerAttached = false;let didInitialPin = false;+// One server watcher for external iCloud changes, including atomic replacement+// and recovery after transient unreadability; never one poll per browser.+let watchedPath = null;+let storeWatchTimer = null;+let watchGeneration = 0;+function configureStoreWatcher(settings) {+ const path = settings?.mortalloom?.enabled ? normalizePath(settings.mortalloom.path) : null;+ if (path === watchedPath) return;+ if (storeWatchTimer) clearInterval(storeWatchTimer);+ storeWatchTimer = null;+ watchedPath = path;+ const generation = ++watchGeneration;+ if (!path) return;+ let previous = null;+ let pending = false;+ let dirty = false;+ const refresh = async () => {+ if (pending) { dirty = true; return; }+ pending = true;+ try {+ do {+ dirty = false;+ const result = await readStoreAtPathResult(path);+ if (generation !== watchGeneration) return;+ // Retain the last good snapshot through eviction/read failures.+ if (result.ok) {+ invalidateMortalLoomChanges(previous, result.store);+ previous = structuredClone(result.store);+ }+ } while (dirty);+ } finally {+ pending = false;+ }+ };+ const changed = () => refresh().catch(err => console.error(`❌ MortalLoom change watcher failed: ${err.message}`));+ storeWatchTimer = setInterval(changed, 10_000);+ storeWatchTimer.unref?.();+ changed();+}+export function _resetMortalLoomInitForTest() {+ if (storeWatchTimer) clearInterval(storeWatchTimer);+ storeWatchTimer = null;+ watchedPath = null;+ watchGeneration += 1;listenerAttached = false;didInitialPin = false;lastPinnedPath = null;@@ -227,6 +272,11 @@ export async function initMortalLoomStore() {// the durable half of this hook.if (!listenerAttached) {settingsEvents.on('settings:updated', (settings) => {+ const nextPath = settings?.mortalloom?.enabled ? normalizePath(settings.mortalloom.path) : null;+ if (nextPath !== watchedPath) {+ configureStoreWatcher(settings);+ invalidateMeatspace(['overview', 'alcohol', 'body', 'blood', 'epigenetic', 'eyes', 'calendar']);+ }if (!settings?.mortalloom?.enabled) {// Disable clears the dedup cache so a future re-enable (even with the// same path) triggers another materialize attempt — otherwise toggling@@ -249,6 +299,7 @@ export async function initMortalLoomStore() {// and could half-fail (first succeeds, second hits a transient and skips// the boot pin even though sync was confirmed enabled).const s = await getSettings();+ configureStoreWatcher(s);if (s?.mortalloom?.enabled) {pinAgainstEviction(normalizePath(s.mortalloom.path));}@@ -446,8 +497,10 @@ export async function updateStore(mutator) {}const base = store || {};for (const k of ARRAY_KEYS) if (!Array.isArray(base[k])) base[k] = [];+ const before = structuredClone(base);const result = await mutator(base);await writeStoreAtPath(path, base);+ invalidateMortalLoomChanges(before, base);return result;}diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.jsindex ac7739199f..8787b46ab9 100644--- a/server/services/mortalLoomStore.test.js+++ b/server/services/mortalLoomStore.test.js@@ -1092,3 +1092,63 @@ describe('evicted (dataless) iCloud store', () => {expect(readFileMock).toHaveBeenCalledWith(UBIQUITY_PATH, 'utf-8');});});++describe('overview invalidation from MortalLoom', () => {+ it('emits the changed collection only after persistence and suppresses failed writes', async () => {+ const { meatspaceEvents } = await import('./meatspaceEvents.js');+ const changed = vi.fn();+ meatspaceEvents.on('changed', changed);+ try {+ readFileMock.mockResolvedValue(JSON.stringify({ bloodTests: [] }));+ let persist;+ writeFileMock.mockImplementationOnce(() => new Promise(resolve => { persist = resolve; }));+ const writing = store.mlPush('bloodTests', { date: '2026-01-01', markers: { example: 1 } });+ await vi.waitFor(() => expect(persist).toBeTypeOf('function'));+ expect(changed).not.toHaveBeenCalled();+ persist();+ await writing;+ expect(changed).toHaveBeenCalledWith({ resources: ['blood'] });+ changed.mockClear();+ writeFileMock.mockRejectedValueOnce(new Error('write failed'));+ await expect(store.mlPush('bloodTests', { date: '2026-01-02' })).rejects.toThrow('write failed');+ expect(changed).not.toHaveBeenCalled();+ } finally { meatspaceEvents.off('changed', changed); }+ });++ it('uses one watcher, detects external edits, retries failed reads and stops when disabled', async () => {+ vi.useFakeTimers();+ store._resetMortalLoomInitForTest();+ settingsEvents.removeAllListeners();+ const { meatspaceEvents } = await import('./meatspaceEvents.js');+ const changed = vi.fn();+ meatspaceEvents.on('changed', changed);+ try {+ readFileMock.mockResolvedValue(JSON.stringify({ bodyEntries: [] }));+ await store.initMortalLoomStore();+ await store.initMortalLoomStore();+ await vi.advanceTimersByTimeAsync(0);+ changed.mockClear();+ readFileMock.mockResolvedValue(JSON.stringify({ bodyEntries: [{ date: '2026-01-01', weightLbs: 170 }] }));+ await vi.advanceTimersByTimeAsync(10_000);+ expect(changed).toHaveBeenCalledExactlyOnceWith({ resources: ['body'] });+ changed.mockClear();+ readFileMock.mockRejectedValueOnce(Object.assign(new Error('unreadable'), { code: 'EACCES' }));+ await vi.advanceTimersByTimeAsync(10_000);+ expect(changed).not.toHaveBeenCalled();+ readFileMock.mockResolvedValue(JSON.stringify({ bodyEntries: [{ date: '2026-01-01', weightLbs: 172 }] }));+ await vi.advanceTimersByTimeAsync(10_000);+ expect(changed).toHaveBeenCalledExactlyOnceWith({ resources: ['body'] });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: false } });+ changed.mockClear();+ const reads = readFileMock.mock.calls.length;+ await vi.advanceTimersByTimeAsync(30_000);+ expect(readFileMock).toHaveBeenCalledTimes(reads);+ expect(changed).not.toHaveBeenCalled();+ } finally {+ store._resetMortalLoomInitForTest();+ settingsEvents.removeAllListeners();+ meatspaceEvents.off('changed', changed);+ vi.useRealTimers();+ }+ });+});diff --git a/server/services/socket.js b/server/services/socket.jsindex a14b3bafa1..3d9ef9993e 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -241,6 +241,7 @@ function setupEventForwarding() {setupAgentEventForwarding();setupBrainEventForwarding();setupDigitalTwinEventForwarding();+ meatspaceEvents.on('changed', payload => ioInstance?.emit('meatspace:changed', payload));setupMoltworldWsEventForwarding();setupMoltworldQueueEventForwarding();setupInstanceEventForwarding();diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 2326b2eeb0..53528d0e6e 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -1,4 +1,4 @@-import { meatspaceEvents } from './meatspaceEvents.js';+import { meatspaceEvents, invalidateMeatspace } from './meatspaceEvents.js';import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated } from './sharing/recordEvents.js';import { fableLoomRunEvents } from './fableLoom/runEvents.js';import { trainingEvents } from './loraTraining/events.js';@@ -167,6 +167,12 @@ describe('socket.js — initSocket', () => {expect(io.emitted).toEqual(Array.from({ length: 5 }, () => ['digital-twin:changed', {}]));});+ it('forwards bounded MeatSpace invalidations', () => {+ io.emitted.length = 0;+ invalidateMeatspace(['body', 'blood']);+ expect(io.emitted).toEqual([['meatspace:changed', { resources: ['body', 'blood'] }]]);+ });+it('forwards persisted Brain changes as bounded invalidations', () => {const dispatch = (event, payload) => {const listener = queueListeners.brain.find(([name]) => name === event)?.[1];