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: preflight personal data imports and legacy mirrors (#6972)
[._.]/ Adam Eivyfdaf83606289
diff --git a/server/services/character.js b/server/services/character.jsindex 8d2e36b767..3a5d073676 100644--- a/server/services/character.js+++ b/server/services/character.js@@ -254,6 +254,7 @@ export async function updateCharacterFields(patch = {}) {// persisted, and new peers ignore the remote level (applyCharacterRemote no longer merges it),// so this projection is invisible to same-version installs.export async function getWireCharacter() {+ // Export participates in a later merge: unreadable state must not masquerade as absence.const raw = await readJSONFile(CHARACTER_FILE, null, { strict: true });if (!raw) return null;// Strip every derived field a hand-edited or legacy character.json might be carrying beforediff --git a/server/services/meatspace.js b/server/services/meatspace.jsindex 4862ed56a0..029d581e16 100644--- a/server/services/meatspace.js+++ b/server/services/meatspace.js@@ -282,7 +282,8 @@ async function migrateBirthDateFromGoals(config) {return queueConfigWrite(async () => {const freshConfig = await loadConfig();if (freshConfig.birthDate) return freshConfig;- const goals = await readJSONFile(GOALS_FILE, null, { strict: true });+ // Read-only migration source: an unreadable legacy file skips migration without writing either file.+ const goals = await readJSONFile(GOALS_FILE, null);if (!goals?.birthDate) return freshConfig;freshConfig.birthDate = goals.birthDate;freshConfig.updatedAt = new Date().toISOString();@@ -315,6 +316,8 @@ export async function getBirthDateStrict() {}export async function updateBirthDate(birthDate, { syncGoals = true } = {}) {+ // Verify the compatibility mirror before committing the canonical config.+ const goals = syncGoals ? await readJSONFile(GOALS_FILE, null, { strict: true }) : null;await queueConfigWrite(async () => {const config = await loadConfig();config.birthDate = birthDate;@@ -323,13 +326,10 @@ export async function updateBirthDate(birthDate, { syncGoals = true } = {}) {});// Keep goals.json in sync for backward compatibility- if (syncGoals) {- const goals = await readJSONFile(GOALS_FILE, null, { strict: true });- if (goals) {- goals.birthDate = birthDate;- goals.updatedAt = new Date().toISOString();- await atomicWrite(join(PATHS.digitalTwin, 'goals.json'), goals);- }+ if (goals) {+ goals.birthDate = birthDate;+ goals.updatedAt = new Date().toISOString();+ await atomicWrite(GOALS_FILE, goals);}await mlPatchProfileIfEnabled({ birthDate });diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.jsindex 123e50ee58..b395960ed1 100644--- a/server/services/meatspaceAlcohol.js+++ b/server/services/meatspaceAlcohol.js@@ -211,7 +211,7 @@ export async function logDrink({ name, oz, abv, count = 1, date }) {return { drink, standardDrinks, date: targetDate, dayTotal: entry?.alcohol?.standardDrinks || standardDrinks };}- const log = await loadDailyLog();+ const log = await loadDailyLog({ strict: true });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 };@@ -254,7 +254,7 @@ export async function updateDrink(date, index, updates) {date: effectiveDate };}- const log = await loadDailyLog();+ const log = await loadDailyLog({ strict: true });const entry = log.entries.find(e => e.date === date);if (!entry?.alcohol?.drinks?.[index]) return null;@@ -311,7 +311,7 @@ export async function removeDrink(date, index) {return removed;}- const log = await loadDailyLog();+ const log = await loadDailyLog({ strict: true });const entry = log.entries.find(e => e.date === date);if (!entry?.alcohol?.drinks?.[index]) return null;diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.jsindex ef59a7a9b2..54f99820c8 100644--- a/server/services/meatspaceNicotine.js+++ b/server/services/meatspaceNicotine.js@@ -165,7 +165,7 @@ export async function logNicotine({ product, mgPerUnit, count = 1, date }) {return { item, totalMg, date: targetDate, dayTotal: entry?.nicotine?.totalMg || totalMg };}- const log = await loadDailyLog();+ const log = await loadDailyLog({ strict: true });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 };@@ -201,7 +201,7 @@ export async function updateNicotine(date, index, updates) {date: effectiveDate };}- const log = await loadDailyLog();+ const log = await loadDailyLog({ strict: true });const entry = log.entries.find(e => e.date === date);if (!entry?.nicotine?.items?.[index]) return null;@@ -257,7 +257,7 @@ export async function removeNicotine(date, index) {return removed;}- const log = await loadDailyLog();+ const log = await loadDailyLog({ strict: true });const entry = log.entries.find(e => e.date === date);if (!entry?.nicotine?.items?.[index]) return null;diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsindex 87db3603b8..3a8678fbc2 100644--- a/server/services/mortalLoomStore.js+++ b/server/services/mortalLoomStore.js@@ -732,8 +732,26 @@ export async function importToPortOS() {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, [], { strict: true });+ const collectionFiles = [+ ['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']+ ];+ // Preflight all destinations before the first write; one unreadable local file+ // must not turn the import into an unreported partially applied batch.+ const collections = await Promise.all(collectionFiles.map(async ([mlKey, fileName]) => {+ const mlArr = store[mlKey] || [];+ const localPath = dataPath('meatspace', fileName);+ const local = mlArr.length ? await readJSONFile(localPath, [], { strict: true }) : [];+ return { mlKey, mlArr, localPath, local };+ }));+ const mergeById = async (mlArr, localPath, pathDir, local) => {const localArr = Array.isArray(local) ? local : [];const seen = new Set(localArr.map(x => x.id).filter(Boolean));let added = 0, skipped = 0;@@ -764,20 +782,9 @@ export async function importToPortOS() {}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] || [];+ for (const { mlKey, mlArr, localPath, local } of collections) {if (mlArr.length === 0) { report.added[mlKey] = 0; report.skipped[mlKey] = 0; continue; }- const { added, skipped } = await mergeById(mlArr, dataPath('meatspace', fileName), dataPath('meatspace'));+ const { added, skipped } = await mergeById(mlArr, localPath, dataPath('meatspace'), local);report.added[mlKey] = added; report.skipped[mlKey] = skipped;}diff --git a/server/services/personalStoreReadSafety.test.js b/server/services/personalStoreReadSafety.test.jsindex 2addfc7af7..704c10cf9b 100644--- a/server/services/personalStoreReadSafety.test.js+++ b/server/services/personalStoreReadSafety.test.js@@ -1,4 +1,4 @@-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { mkdir, readFile, rm, writeFile } from 'fs/promises';import { dirname, join } from 'path';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';@@ -12,9 +12,11 @@ vi.mock('fs/promises', async (original) => {});vi.mock('../lib/fileUtils.js', async (original) => makePathsProxy(await original(), {dataRoot: () => lazyTempDataRoot('portos-personal-read-safety-'),+ overrides: { dataPath: (...parts) => join(lazyTempDataRoot('portos-personal-read-safety-'), ...parts) },}));vi.mock('../lib/paths.js', async (original) => makePathsProxy(await original(), {dataRoot: () => lazyTempDataRoot('portos-personal-read-safety-'),+ overrides: { dataPath: (...parts) => join(lazyTempDataRoot('portos-personal-read-safety-'), ...parts) },}));vi.mock('./userTimezone.js', () => ({ getUserTimezone: async () => 'UTC', userLocalToday: async () => '2026-01-02' }));vi.mock('./characterSkills.js', () => ({ getCharacterSkills: async () => [] }));@@ -37,33 +39,68 @@ vi.mock('./calendarSync.js', () => ({}));vi.mock('./calendarAccounts.js', () => ({}));vi.mock('./identity.js', () => ({ addProgressEntry: vi.fn(), getGoals: async () => ({ goals: [] }) }));+vi.mock('./settings.js', async () => {+ const { EventEmitter } = await import('events');+ return { settingsEvents: new EventEmitter(), getSettings: async () => ({+ mortalloom: { enabled: false, path: join(lazyTempDataRoot('portos-personal-read-safety-'), 'mortal-source.json') },+ }) };+});vi.mock('./cosAgentLifecycle.js', () => ({ getAgents: async () => [] }));vi.mock('./digital-twin-meta.js', () => ({ loadMeta: async () => ({}), saveMeta: vi.fn() }));vi.mock('./taste-questionnaire.js', () => ({ invalidateTasteProfileCache: vi.fn() }));import { PATHS } from '../lib/fileUtils.js';-import { mergeIntoDay } from './appleHealthIngest.js';-import { saveStory, updateConfig } from './autobiography.js';-import { updateCharacterFields } from './character.js';-import { markDriverHandled } from './dailyDriver.js';-import { confirmEvent } from './dailyReview.js';-import { updateBirthDate } from './meatspace.js';-import { addCustomDrink } from './meatspaceAlcohol.js';-import { addActivity, addLifeEvent } from './meatspaceCalendar.js';-import { addCustomProduct } from './meatspaceNicotine.js';-import { setKochLevel } from './meatspacePostMorse.js';-import { saveStoredPostSession, saveStoredTrainingRun } from './postRunStore.js';-import { aggregateTwinEvidence } from './twinEnrichment.js';-import { listJournals, _clearObsidianLocationsCacheForTest } from './brainJournal.js';--import { updatePostConfig } from './meatspacePost.js';-import { createMemoryItem } from './meatspacePostMemory.js';-import { applySessionToReviewSchedule } from './meatspacePostReview.js';-import { onTaskCompleted } from './productivity.js';-import { recordUserAction } from './userActions.js';-import { getDigitalTwinSnapshot, applyDigitalTwinRemote } from './digital-twin-sync.js';+let { mergeIntoDay } = {};+let { saveStory, updateConfig } = {};+let { updateCharacterFields } = {};+let { markDriverHandled } = {};+let { confirmEvent } = {};+let { updateBirthDate } = {};+let { addCustomDrink, logDrink } = {};+let { addActivity, addLifeEvent } = {};+let { addCustomProduct, logNicotine } = {};+let { setKochLevel } = {};+let { saveStoredPostSession, saveStoredTrainingRun } = {};+let { aggregateTwinEvidence } = {};+let { listJournals, _clearObsidianLocationsCacheForTest } = {};++let { updatePostConfig } = {};+let { createMemoryItem } = {};+let { applySessionToReviewSchedule } = {};+let { onTaskCompleted } = {};+let { recordUserAction } = {};+let { getDigitalTwinSnapshot, applyDigitalTwinRemote } = {};+++// Load service boundaries only after the isolated filesystem and dependency mocks are installed.+beforeAll(async () => {+ ({ mergeIntoDay } = await import('./appleHealthIngest.js'));+ ({ saveStory, updateConfig } = await import('./autobiography.js'));+ ({ updateCharacterFields } = await import('./character.js'));+ ({ markDriverHandled } = await import('./dailyDriver.js'));+ ({ confirmEvent } = await import('./dailyReview.js'));+ ({ updateBirthDate } = await import('./meatspace.js'));+ ({ addCustomDrink, logDrink } = await import('./meatspaceAlcohol.js'));+ ({ addActivity, addLifeEvent } = await import('./meatspaceCalendar.js'));+ ({ addCustomProduct, logNicotine } = await import('./meatspaceNicotine.js'));+ ({ setKochLevel } = await import('./meatspacePostMorse.js'));+ ({ saveStoredPostSession, saveStoredTrainingRun } = await import('./postRunStore.js'));+ ({ aggregateTwinEvidence } = await import('./twinEnrichment.js'));+ ({ listJournals, _clearObsidianLocationsCacheForTest } = await import('./brainJournal.js'));+ ({ updatePostConfig } = await import('./meatspacePost.js'));+ ({ createMemoryItem } = await import('./meatspacePostMemory.js'));+ ({ applySessionToReviewSchedule } = await import('./meatspacePostReview.js'));+ ({ onTaskCompleted } = await import('./productivity.js'));+ ({ recordUserAction } = await import('./userActions.js'));+ ({ getDigitalTwinSnapshot, applyDigitalTwinRemote } = await import('./digital-twin-sync.js'));+});++let importToPortOS;+beforeAll(async () => { ({ importToPortOS } = await import('./mortalLoomStore.js')); });const cases = [+ ['alcohol daily log', () => join(PATHS.meatspace, 'daily-log.json'), () => logDrink({ name: 'Example', oz: 12, abv: 5, date: '2026-01-02' })],+ ['nicotine daily log', () => join(PATHS.meatspace, 'daily-log.json'), () => logNicotine({ product: 'Example', mgPerUnit: 1, date: '2026-01-02' })],['POST config', () => join(PATHS.meatspace, 'post-config.json'), () => updatePostConfig({ enabled: true })],['memory items', () => join(PATHS.meatspace, 'post-memory-items.json'), () => createMemoryItem({ title: 'Example', lines: ['Example line'] })],['review schedule', () => join(PATHS.meatspace, 'post-review-schedule.json'), () => applySessionToReviewSchedule({ masteredSkills: [{ skillId: 'example' }] })],@@ -73,7 +110,7 @@ const cases = [['autobiography stories', () => join(PATHS.digitalTwin, 'autobiography/stories.json'), () => saveStory({ promptId: 'childhood-0', content: 'Example memory' })],['autobiography config', () => join(PATHS.digitalTwin, 'autobiography/config.json'), () => updateConfig({ enabled: true })],['character', () => join(PATHS.data, 'character.json'), () => updateCharacterFields({ name: 'Example character' })],- ['daily driver', () => join(PATHS.data, 'daily-driver.json'), markDriverHandled],+ ['daily driver', () => join(PATHS.data, 'daily-driver.json'), () => markDriverHandled()],['daily review', () => join(PATHS.calendar, 'daily-reviews/2026-01-02.json'), () => confirmEvent('2026-01-02', { eventId: 'example', happened: false })],['meatspace config', () => join(PATHS.meatspace, 'config.json'), () => updateBirthDate('2000-01-01', { syncGoals: false })],['custom drinks', () => join(PATHS.meatspace, 'custom-drinks.json'), () => addCustomDrink({ name: 'Example', oz: 12, abv: 5 })],@@ -83,7 +120,7 @@ const cases = [['Morse progress', () => join(PATHS.meatspace, 'post-morse-progress.json'), () => setKochLevel({ kochLevel: 3 })],['POST sessions', () => join(PATHS.meatspace, 'post-sessions.json'), () => saveStoredPostSession({ id: 'example-run', date: '2026-01-02' })],['POST training', () => join(PATHS.meatspace, 'post-training-log.json'), () => saveStoredTrainingRun({ id: 'example-run', localDay: '2026-01-02', attempts: [{ id: 'example-attempt', skill: 'memory' }] })],- ['taste evidence', () => join(PATHS.digitalTwin, 'taste-observed.json'), aggregateTwinEvidence],+ ['taste evidence', () => join(PATHS.digitalTwin, 'taste-observed.json'), () => aggregateTwinEvidence()],];beforeEach(async () => {@@ -158,3 +195,31 @@ it('blocks Digital Twin merge and export on unreadable local records, then preseawait applyDigitalTwinRemote(incoming);expect(JSON.parse(await readFile(path, 'utf8')).stories.map(story => story.id).sort()).toEqual(['incoming', 'retained']);});++it('checks the legacy goals mirror before changing the canonical birth date', async () => {+ const configPath = join(PATHS.meatspace, 'config.json');+ const goalsPath = join(PATHS.digitalTwin, 'goals.json');+ const config = JSON.stringify({ birthDate: '2000-01-01' });+ await seed(configPath, config);+ await seed(goalsPath, '{');+ await expect(updateBirthDate('2001-01-01')).rejects.toThrow(/Unreadable JSON file/);+ expect(await readFile(configPath, 'utf8')).toBe(config);+ expect(await readFile(goalsPath, 'utf8')).toBe('{');+});++it('preflights MortalLoom import destinations and preserves repaired records on retry', async () => {+ const source = join(PATHS.data, 'mortal-source.json');+ const goalsPath = join(PATHS.digitalTwin, 'goals.json');+ const alcoholPath = join(PATHS.meatspace, 'alcohol-drinks.json');+ const goals = JSON.stringify({ goals: [{ id: 'retained-goal' }] });+ await seed(source, JSON.stringify({ goals: [{ id: 'incoming-goal' }], alcoholDrinks: [{ id: 'incoming-drink' }] }));+ await seed(goalsPath, goals);+ await seed(alcoholPath, '{');+ await expect(importToPortOS()).rejects.toThrow(/Unreadable JSON file/);+ expect(await readFile(goalsPath, 'utf8')).toBe(goals);+ expect(await readFile(alcoholPath, 'utf8')).toBe('{');+ await seed(alcoholPath, JSON.stringify([{ id: 'retained-drink' }]));+ await expect(importToPortOS()).resolves.toMatchObject({ ok: true });+ expect(JSON.parse(await readFile(goalsPath, 'utf8')).goals.map(goal => goal.id)).toEqual(['retained-goal', 'incoming-goal']);+ expect(JSON.parse(await readFile(alcoholPath, 'utf8')).map(drink => drink.id)).toEqual(['retained-drink', 'incoming-drink']);+});diff --git a/server/services/twinEnrichment.js b/server/services/twinEnrichment.jsindex 26b29cf873..92a3cedee1 100644--- a/server/services/twinEnrichment.js+++ b/server/services/twinEnrichment.js@@ -335,6 +335,7 @@ function daysAgoIso(days, now) {// ---------------------------------------------------------------------------export async function getTasteEvidence() {+ // Durable despite the derived rollups: aggregate and interpret retain user-authored interpretation.return readJSONFile(TASTE_OBSERVED_FILE, null, { strict: true });}