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: serialize MeatSpace config mutations
Adam Eivy2ec61462c874
diff --git a/server/services/meatspace.configWrites.test.js b/server/services/meatspace.configWrites.test.jsnew file mode 100644index 0000000000..af9c5afd84--- /dev/null+++ b/server/services/meatspace.configWrites.test.js@@ -0,0 +1,82 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const store = vi.hoisted(() => ({+ config: null,+ goals: null+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: {+ data: '/tmp/portos-test-data',+ meatspace: '/tmp/portos-test-data/meatspace',+ digitalTwin: '/tmp/portos-test-data/digital-twin'+ },+ atomicWrite: vi.fn(async (_path, value) => { store.config = structuredClone(value); }),+ ensureDir: vi.fn(async () => {}),+ readJSONFile: vi.fn(async (path, fallback) => {+ const value = path.endsWith('goals.json') ? store.goals : store.config;+ return value === null ? structuredClone(fallback) : structuredClone(value);+ }),+ readJSONFileStrict: vi.fn(async () => ({ ok: true, value: store.config }))+}));+vi.mock('./genome.js', () => ({ getSnpIndex: vi.fn(async () => new Map([['Y', { chromosome: 'Y' }]])) }));+vi.mock('./meatspaceDailyLog.js', () => ({ readLocalDailyLog: vi.fn(async () => null) }));+vi.mock('./mortalLoomStore.js', () => ({+ mlGetProfileIfEnabled: vi.fn(async () => null),+ mlPatchProfileIfEnabled: vi.fn(async () => {})+}));+vi.mock('fs/promises', () => ({ readFile: vi.fn(async () => '{}') }));++const meatspace = await import('./meatspace.js');++const initialConfig = () => ({+ birthDate: null,+ sex: null,+ sexSource: null,+ lifestyle: {+ smokingStatus: 'never',+ exerciseMinutesPerWeek: 150,+ sleepHoursPerNight: 7.5,+ dietQuality: 'good',+ stressLevel: 'moderate',+ bmi: null,+ chronicConditions: []+ },+ updatedAt: null+});++describe('meatspace config write serialization (#4913)', () => {+ beforeEach(() => {+ store.config = initialConfig();+ store.goals = null;+ });++ it('retains simultaneous config and lifestyle patches', async () => {+ await Promise.all([+ meatspace.updateConfig({ sex: 'female', sexSource: 'manual' }),+ meatspace.updateLifestyle({ sleepHoursPerNight: 8 })+ ]);++ expect(store.config).toMatchObject({+ sex: 'female',+ sexSource: 'manual',+ lifestyle: { sleepHoursPerNight: 8 }+ });+ });++ it('preserves a migrated birth date until a queued update supersedes it', async () => {+ store.goals = { birthDate: '1970-01-01' };+ expect(await meatspace.getBirthDate()).toEqual({ birthDate: '1970-01-01' });++ await Promise.all([+ meatspace.getConfig(),+ meatspace.updateBirthDate('1980-01-01', { syncGoals: false })+ ]);++ expect(store.config).toMatchObject({+ sex: 'female',+ sexSource: 'genome',+ birthDate: '1980-01-01'+ });+ });+});diff --git a/server/services/meatspace.js b/server/services/meatspace.jsindex eb64e2cb82..91489d4899 100644--- a/server/services/meatspace.js+++ b/server/services/meatspace.js@@ -8,6 +8,7 @@import { readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile, readJSONFileStrict } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { isPlainObject } from '../lib/objects.js';import { readLocalDailyLog } from './meatspaceDailyLog.js';import { getSnpIndex } from './genome.js';@@ -31,6 +32,7 @@ function pickMortalLoomLifestyle(lifestyle) {const MEATSPACE_DIR = PATHS.meatspace;const CONFIG_FILE = join(MEATSPACE_DIR, 'config.json');+const queueConfigWrite = createFileWriteQueue();// Digital Twin paths (read-only)const LONGEVITY_FILE = join(PATHS.digitalTwin, 'longevity.json');@@ -200,17 +202,22 @@ export function computeLEV(birthDate, adjustedLE) {// === Exported Service Functions ===export async function getConfig() {- const config = await loadConfig();+ let config = await loadConfig();// Auto-detect sex from genome if not setif (!config.sex) {const detectedSex = await detectSexFromGenome();if (detectedSex) {- config.sex = detectedSex;- config.sexSource = 'genome';- config.updatedAt = new Date().toISOString();- await saveConfig(config);- console.log(`🧬 Sex auto-detected from genome: ${detectedSex}`);+ config = await queueConfigWrite(async () => {+ const freshConfig = await loadConfig();+ if (freshConfig.sex) return freshConfig;+ freshConfig.sex = detectedSex;+ freshConfig.sexSource = 'genome';+ freshConfig.updatedAt = new Date().toISOString();+ await saveConfig(freshConfig);+ console.log(`🧬 Sex auto-detected from genome: ${detectedSex}`);+ return freshConfig;+ });}}@@ -232,14 +239,17 @@ export async function getConfig() {}export async function updateConfig(updates) {- const config = await loadConfig();- if (updates.sex !== undefined) config.sex = updates.sex;- if (updates.sexSource !== undefined) config.sexSource = updates.sexSource;- if (updates.lifestyle) {- config.lifestyle = { ...config.lifestyle, ...updates.lifestyle };- }- config.updatedAt = new Date().toISOString();- await saveConfig(config);+ const config = await queueConfigWrite(async () => {+ const config = await loadConfig();+ if (updates.sex !== undefined) config.sex = updates.sex;+ if (updates.sexSource !== undefined) config.sexSource = updates.sexSource;+ if (updates.lifestyle) {+ config.lifestyle = { ...config.lifestyle, ...updates.lifestyle };+ }+ config.updatedAt = new Date().toISOString();+ await saveConfig(config);+ return config;+ });const mlPatch = {};if (updates.sex !== undefined) mlPatch.biologicalSex = updates.sex || null;@@ -251,10 +261,13 @@ export async function updateConfig(updates) {}export async function updateLifestyle(updates) {- const config = await loadConfig();- config.lifestyle = { ...config.lifestyle, ...updates };- config.updatedAt = new Date().toISOString();- await saveConfig(config);+ const config = await queueConfigWrite(async () => {+ const config = await loadConfig();+ config.lifestyle = { ...config.lifestyle, ...updates };+ config.updatedAt = new Date().toISOString();+ await saveConfig(config);+ return config;+ });const mlLifestyle = pickMortalLoomLifestyle(updates);if (mlLifestyle) await mlPatchProfileIfEnabled({ lifestyle: mlLifestyle });@@ -266,13 +279,17 @@ export async function updateLifestyle(updates) {async function migrateBirthDateFromGoals(config) {if (config.birthDate) return config;- const goals = await readJSONFile(GOALS_FILE, null);- if (!goals?.birthDate) return config;- config.birthDate = goals.birthDate;- config.updatedAt = new Date().toISOString();- await saveConfig(config);- console.log(`📅 Migrated birthDate from goals.json to meatspace config`);- return config;+ return queueConfigWrite(async () => {+ const freshConfig = await loadConfig();+ if (freshConfig.birthDate) return freshConfig;+ const goals = await readJSONFile(GOALS_FILE, null);+ if (!goals?.birthDate) return freshConfig;+ freshConfig.birthDate = goals.birthDate;+ freshConfig.updatedAt = new Date().toISOString();+ await saveConfig(freshConfig);+ console.log(`📅 Migrated birthDate from goals.json to meatspace config`);+ return freshConfig;+ });}export async function getBirthDate() {@@ -298,10 +315,12 @@ export async function getBirthDateStrict() {}export async function updateBirthDate(birthDate, { syncGoals = true } = {}) {- const config = await loadConfig();- config.birthDate = birthDate;- config.updatedAt = new Date().toISOString();- await saveConfig(config);+ await queueConfigWrite(async () => {+ const config = await loadConfig();+ config.birthDate = birthDate;+ config.updatedAt = new Date().toISOString();+ await saveConfig(config);+ });// Keep goals.json in sync for backward compatibilityif (syncGoals) {