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
refactor: collapse the three near-identical daily-log.json readers into one shared loader (#4112)
[._.]/ Adam Eivy7291826c3f58
diff --git a/.changelog/next/changed-issue-4112.md b/.changelog/next/changed-issue-4112.mdnew file mode 100644index 0000000000..3519927df1--- /dev/null+++ b/.changelog/next/changed-issue-4112.md@@ -0,0 +1 @@+- De-duplicated the MeatSpace daily-log readers: alcohol, nicotine, and body-composition now share one loader instead of three near-identical copiesdiff --git a/server/routes/meatspaceExportRoutes.js b/server/routes/meatspaceExportRoutes.jsindex d957ad6bbf..0693f97490 100644--- a/server/routes/meatspaceExportRoutes.js+++ b/server/routes/meatspaceExportRoutes.js@@ -6,10 +6,9 @@*/import { Router } from 'express';-import { join } from 'path';import crypto from 'node:crypto';import { asyncHandler } from '../lib/errorHandler.js';-import { PATHS, readJSONFile } from '../lib/fileUtils.js';+import { readLocalDailyLog } from '../services/meatspaceDailyLog.js';import * as meatspaceService from '../services/meatspace.js';import * as alcoholService from '../services/meatspaceAlcohol.js';import * as nicotineService from '../services/meatspaceNicotine.js';@@ -29,7 +28,7 @@ router.get('/export/mortalloom', asyncHandler(async (req, res) => {healthService.getBloodTests(),healthService.getEpigeneticTests(),healthService.getEyeExams(),- readJSONFile(join(PATHS.meatspace, 'daily-log.json'), { entries: [] }),+ readLocalDailyLog(),alcoholService.getCustomDrinks(),nicotineService.getCustomProducts(),getGoals(),diff --git a/server/services/meatspace.js b/server/services/meatspace.jsindex a33df23981..c90ee5dbae 100644--- a/server/services/meatspace.js+++ b/server/services/meatspace.js@@ -9,6 +9,7 @@ import { readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile, readJSONFileStrict } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';+import { readLocalDailyLog } from './meatspaceDailyLog.js';import { getSnpIndex } from './genome.js';import { mlGetProfileIfEnabled, mlPatchProfileIfEnabled } from './mortalLoomStore.js';@@ -30,7 +31,6 @@ function pickMortalLoomLifestyle(lifestyle) {const MEATSPACE_DIR = PATHS.meatspace;const CONFIG_FILE = join(MEATSPACE_DIR, 'config.json');-const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');// Digital Twin paths (read-only)const LONGEVITY_FILE = join(PATHS.digitalTwin, 'longevity.json');@@ -355,7 +355,7 @@ export async function getOverview() {getConfig(),getDeathClock(),getLEV(),- readJSONFile(DAILY_LOG_FILE, { entries: [] })+ readLocalDailyLog()]);const entryCount = dailyLog.entries?.length || 0;diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.jsindex a03846bfc9..ec1201ecfe 100644--- a/server/services/meatspaceAlcohol.js+++ b/server/services/meatspaceAlcohol.js@@ -8,9 +8,9 @@import { readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';+import { DAILY_LOG_FILE, loadMeatspaceDailyLog } from './meatspaceDailyLog.js';import {isMortalLoomEnabled,- readDailyLogIfEnabled,mlPush,mlPatchById,mlRemoveById,@@ -18,7 +18,6 @@ import {} from './mortalLoomStore.js';const MEATSPACE_DIR = PATHS.meatspace;-const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');const CONFIG_FILE = join(MEATSPACE_DIR, 'config.json');const CUSTOM_DRINKS_FILE = join(MEATSPACE_DIR, 'custom-drinks.json');@@ -145,20 +144,7 @@ export function computeRollingAverages(entries, sex = 'male') {* default so the UI keeps degrading gracefully; the health-logging COUNT opts in,* because a fake 0 there reads as "you have never logged anything" (#2726).*/-async function loadDailyLog({ strict = false } = {}) {- const ml = await readDailyLogIfEnabled({ strict });- if (ml) return ml;- const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false, strict });- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {- if (strict) throw new Error(`Alcohol daily log malformed: ${DAILY_LOG_FILE}`);- return { entries: [], lastEntryDate: null };- }- if (!Array.isArray(raw.entries)) {- if (strict) throw new Error(`Alcohol daily log malformed: ${DAILY_LOG_FILE}`);- raw.entries = [];- }- return raw;-}+const loadDailyLog = (options) => loadMeatspaceDailyLog({ ...options, label: 'Alcohol' });async function saveDailyLog(log) {await ensureDir(MEATSPACE_DIR);diff --git a/server/services/meatspaceDailyLog.js b/server/services/meatspaceDailyLog.jsnew file mode 100644index 0000000000..5389eea8ef--- /dev/null+++ b/server/services/meatspaceDailyLog.js@@ -0,0 +1,71 @@+/**+ * MeatSpace Daily Log Reader+ *+ * `data/meatspace/daily-log.json` is one file with several tenants — alcohol,+ * nicotine, and body-composition entries all live on the same day-keyed records —+ * so every one of those services needs to read it. They each used to carry their+ * own copy of the read: same MortalLoom probe, same `{ entries: [], lastEntryDate:+ * null }` default, same shape validation, same `{ strict }` branch (#2726). This is+ * the single copy they all delegate to (#4112).+ *+ * Two entry points, because the MortalLoom half is not universal:+ * - `loadMeatspaceDailyLog` — the full read, MortalLoom-first. Correct for the+ * alcohol/nicotine services, whose records MortalLoom composes INTO a daily log+ * (`readDailyLogIfEnabled`).+ * - `readLocalDailyLog` — the local mirror only. Correct for callers that either+ * probe MortalLoom on a different key first (body entries come from the+ * `bodyEntries` array, not the composed daily log) or deliberately read only the+ * local file (export, overview).+ *+ * Both keep the sentinel distinction the strict branch exists for: absent is a+ * trustworthy empty, present-but-unreadable/malformed is a failure. Under+ * `strict: true` the second must throw rather than collapse into the first, so a+ * caller that COUNTS these entries can't report a fake 0 (#2726).+ */++import { join } from 'path';+import { PATHS, readJSONFile } from '../lib/fileUtils.js';+import { readDailyLogIfEnabled } from './mortalLoomStore.js';++export const DAILY_LOG_FILE = join(PATHS.meatspace, 'daily-log.json');++// 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 });++/**+ * Read the local `daily-log.json` mirror, without consulting MortalLoom.+ *+ * @param {{ strict?: boolean, label?: string }} [options]+ * `strict: true` throws when the file is present-but-unreadable or shaped wrong,+ * instead of substituting an empty log. Off by default so the UI keeps degrading+ * gracefully. `label` names the domain in the malformed-log error.+ * @returns {Promise<{ entries: object[], lastEntryDate: string|null }>}+ */+export async function readLocalDailyLog({ strict = false, label = 'MeatSpace' } = {}) {+ const raw = await readJSONFile(DAILY_LOG_FILE, emptyDailyLog(), { allowArray: false, strict });+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ if (strict) throw new Error(`${label} daily log malformed: ${DAILY_LOG_FILE}`);+ return emptyDailyLog();+ }+ if (!Array.isArray(raw.entries)) {+ if (strict) throw new Error(`${label} daily log malformed: ${DAILY_LOG_FILE}`);+ raw.entries = [];+ }+ return raw;+}++/**+ * Read the daily log, preferring the MortalLoom-composed view when iCloud sync is+ * on and falling back to the local mirror when it is not.+ *+ * @param {{ strict?: boolean, label?: string }} [options] - see `readLocalDailyLog`.+ * Under `strict` the MortalLoom probe throws on a present-but-unreadable store+ * rather than falling through to a local log that may be a genuine ENOENT (#2742).+ * @returns {Promise<{ entries: object[], lastEntryDate: string|null }>}+ */+export async function loadMeatspaceDailyLog({ strict = false, label = 'MeatSpace' } = {}) {+ const ml = await readDailyLogIfEnabled({ strict });+ if (ml) return ml;+ return readLocalDailyLog({ strict, label });+}diff --git a/server/services/meatspaceDailyLog.test.js b/server/services/meatspaceDailyLog.test.jsnew file mode 100644index 0000000000..67a3715b1b--- /dev/null+++ b/server/services/meatspaceDailyLog.test.js@@ -0,0 +1,192 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// The alcohol, nicotine, and body-composition services all read the same+// daily-log.json. They used to each carry a byte-identical copy of the probe →+// read → validate sequence; #4112 collapsed that into meatspaceDailyLog.js. These+// tests pin the shared reader's behavior AND the delegation from the callers, so+// the strict/#2726 semantics can't drift back apart.++vi.mock('../lib/fileUtils.js', () => ({+ tryReadFile: vi.fn().mockResolvedValue(null),+ readJSONFile: vi.fn(),+ getDateString: vi.fn(() => '2024-06-01'),+ PATHS: {+ root: '/mock',+ data: '/mock/data',+ meatspace: '/mock/data/meatspace'+ },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn().mockResolvedValue(undefined)+}));++vi.mock('./mortalLoomStore.js', () => ({+ isMortalLoomEnabled: vi.fn().mockResolvedValue(false),+ readDailyLogIfEnabled: vi.fn().mockResolvedValue(null),+ mlArrayIfEnabled: vi.fn().mockResolvedValue(null),+ mlPush: vi.fn(),+ mlPatchById: vi.fn(),+ mlRemoveById: vi.fn(),+ mlIdAtDateIndex: vi.fn(),+ mlUpsertHealthMetricByDate: vi.fn()+}));++import { readJSONFile } from '../lib/fileUtils.js';+import { readDailyLogIfEnabled } from './mortalLoomStore.js';+import { DAILY_LOG_FILE, readLocalDailyLog, loadMeatspaceDailyLog } from './meatspaceDailyLog.js';+import { getDailyAlcohol } from './meatspaceAlcohol.js';+import { getDailyNicotine } from './meatspaceNicotine.js';+import { getBodyHistory } from './meatspaceHealth.js';++beforeEach(() => {+ vi.clearAllMocks();+ readDailyLogIfEnabled.mockResolvedValue(null);+});++describe('DAILY_LOG_FILE', () => {+ it('points at daily-log.json under the meatspace data dir', () => {+ expect(DAILY_LOG_FILE).toBe('/mock/data/meatspace/daily-log.json');+ });+});++describe('readLocalDailyLog', () => {+ it('reads the local mirror without consulting MortalLoom', async () => {+ readJSONFile.mockResolvedValue({ entries: [{ date: '2024-03-02' }], lastEntryDate: '2024-03-02' });+ const log = await readLocalDailyLog();+ expect(log.entries).toEqual([{ date: '2024-03-02' }]);+ expect(readDailyLogIfEnabled).not.toHaveBeenCalled();+ });++ it('passes the file, default, and allowArray:false through to readJSONFile', async () => {+ readJSONFile.mockResolvedValue({ entries: [] });+ await readLocalDailyLog({ strict: true, label: 'Alcohol' });+ expect(readJSONFile).toHaveBeenCalledWith(+ '/mock/data/meatspace/daily-log.json',+ { entries: [], lastEntryDate: null },+ { allowArray: false, strict: true }+ );+ });++ it('returns the empty log when the file is absent', async () => {+ readJSONFile.mockResolvedValue({ entries: [], lastEntryDate: null });+ expect(await readLocalDailyLog()).toEqual({ entries: [], lastEntryDate: null });+ });++ it('hands back a fresh empty log each time so callers can mutate it', async () => {+ readJSONFile.mockResolvedValue(null);+ const first = await readLocalDailyLog();+ first.entries.push({ date: '2024-01-01' });+ const second = await readLocalDailyLog();+ expect(second.entries).toEqual([]);+ });++ it('coerces a missing entries array to empty when not strict', async () => {+ readJSONFile.mockResolvedValue({ lastEntryDate: '2024-01-01' });+ expect(await readLocalDailyLog()).toEqual({ entries: [], lastEntryDate: '2024-01-01' });+ });++ it('substitutes the empty log for a non-object root when not strict', async () => {+ readJSONFile.mockResolvedValue([{ date: '2024-01-01' }]);+ expect(await readLocalDailyLog()).toEqual({ entries: [], lastEntryDate: null });+ });++ it('throws with the domain label for a non-object root under strict', async () => {+ readJSONFile.mockResolvedValue([{ date: '2024-01-01' }]);+ await expect(readLocalDailyLog({ strict: true, label: 'Health' }))+ .rejects.toThrow(/Health daily log malformed/);+ });++ it('throws with the domain label for a non-array entries under strict', async () => {+ readJSONFile.mockResolvedValue({ entries: 'nope' });+ await expect(readLocalDailyLog({ strict: true, label: 'Nicotine' }))+ .rejects.toThrow(/Nicotine daily log malformed/);+ });++ it('does not swallow a strict read failure raised by readJSONFile', async () => {+ readJSONFile.mockRejectedValue(new Error('Unreadable JSON file: /mock/data/meatspace/daily-log.json'));+ await expect(readLocalDailyLog({ strict: true })).rejects.toThrow(/Unreadable JSON file/);+ });+});++describe('loadMeatspaceDailyLog', () => {+ it('prefers the MortalLoom-composed log and skips the local read', async () => {+ readDailyLogIfEnabled.mockResolvedValue({ entries: [{ date: '2024-05-05' }], lastEntryDate: '2024-05-05' });+ readJSONFile.mockResolvedValue({ entries: [{ date: '1999-01-01' }] });+ const log = await loadMeatspaceDailyLog();+ expect(log.entries).toEqual([{ date: '2024-05-05' }]);+ expect(readJSONFile).not.toHaveBeenCalled();+ });++ it('falls back to the local mirror when MortalLoom is off', async () => {+ readDailyLogIfEnabled.mockResolvedValue(null);+ readJSONFile.mockResolvedValue({ entries: [{ date: '2024-04-04' }], lastEntryDate: '2024-04-04' });+ const log = await loadMeatspaceDailyLog();+ expect(log.entries).toEqual([{ date: '2024-04-04' }]);+ });++ it('forwards strict to the MortalLoom probe', async () => {+ readJSONFile.mockResolvedValue({ entries: [] });+ await loadMeatspaceDailyLog({ strict: true });+ expect(readDailyLogIfEnabled).toHaveBeenCalledWith({ strict: true });+ });++ it('propagates a strict MortalLoom failure instead of scoring a local empty', async () => {+ readDailyLogIfEnabled.mockRejectedValue(new Error('MortalLoom store unreadable for daily log'));+ readJSONFile.mockResolvedValue({ entries: [] });+ await expect(loadMeatspaceDailyLog({ strict: true })).rejects.toThrow(/unreadable/i);+ expect(readJSONFile).not.toHaveBeenCalled();+ });+});++// The point of the extraction is that the three services actually go through it.+// Each case asserts on a distinctive value or label that only the shared reader+// (driven by the mocked readJSONFile) can produce, so a mock that stopped+// intercepting would fail rather than pass against a default.+describe('caller delegation (#4112)', () => {+ it('routes alcohol reads through the shared reader', async () => {+ readJSONFile.mockResolvedValue({+ entries: [{ date: '2024-02-02', alcohol: { drinks: [{ name: 'Example Lager', oz: 12, abv: 5 }] } }]+ });+ const entries = await getDailyAlcohol();+ expect(entries).toEqual([+ { date: '2024-02-02', alcohol: { drinks: [{ name: 'Example Lager', oz: 12, abv: 5 }] } }+ ]);+ expect(readDailyLogIfEnabled).toHaveBeenCalled();+ });++ it('labels an alcohol strict failure as Alcohol', async () => {+ readJSONFile.mockResolvedValue({ entries: 'nope' });+ await expect(getDailyAlcohol(null, null, { strict: true }))+ .rejects.toThrow(/Alcohol daily log malformed/);+ });++ it('routes nicotine reads through the shared reader', async () => {+ readJSONFile.mockResolvedValue({+ entries: [{ date: '2024-02-03', nicotine: { items: [{ product: 'Example Pouch', mgPerUnit: 3, count: 2 }], totalMg: 6 } }]+ });+ const entries = await getDailyNicotine();+ expect(entries).toHaveLength(1);+ expect(entries[0].nicotine.totalMg).toBe(6);+ expect(readDailyLogIfEnabled).toHaveBeenCalled();+ });++ it('labels a nicotine strict failure as Nicotine', async () => {+ readJSONFile.mockResolvedValue({ entries: 'nope' });+ await expect(getDailyNicotine(null, null, { strict: true }))+ .rejects.toThrow(/Nicotine daily log malformed/);+ });++ it('routes body history through the local reader, not the composed log', async () => {+ readJSONFile.mockResolvedValue({+ entries: [{ date: '2024-02-04', body: { weightLbs: 175 } }]+ });+ expect(await getBodyHistory()).toEqual([{ date: '2024-02-04', weightLbs: 175 }]);+ // Body entries come from MortalLoom's own `bodyEntries` key, so the composed+ // daily-log probe must stay out of this path (see meatspaceHealth.js).+ expect(readDailyLogIfEnabled).not.toHaveBeenCalled();+ });++ it('labels a body-history strict failure as Health', async () => {+ readJSONFile.mockResolvedValue({ entries: 'nope' });+ await expect(getBodyHistory({ strict: true })).rejects.toThrow(/Health daily log malformed/);+ });+});diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.jsindex fad49c2bee..f8facdabb3 100644--- a/server/services/meatspaceHealth.js+++ b/server/services/meatspaceHealth.js@@ -8,6 +8,7 @@import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';+import { DAILY_LOG_FILE, readLocalDailyLog } from './meatspaceDailyLog.js';import {isMortalLoomEnabled,mlArrayIfEnabled,@@ -18,7 +19,6 @@ import {} from './mortalLoomStore.js';const MEATSPACE_DIR = PATHS.meatspace;-const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');const BLOOD_TESTS_FILE = join(MEATSPACE_DIR, 'blood-tests.json');const EPIGENETIC_TESTS_FILE = join(MEATSPACE_DIR, 'epigenetic-tests.json');const EYES_FILE = join(MEATSPACE_DIR, 'eyes.json');@@ -73,12 +73,14 @@ export async function saveBloodTests(data) {* (#2726). Off by default — existing callers keep the empty fallback.*/export async function getBodyHistory({ strict = false } = {}) {+ // Body entries come from MortalLoom's own `bodyEntries` array, NOT the composed+ // daily log the alcohol/nicotine services probe — so this reads the local mirror+ // directly rather than going through `loadMeatspaceDailyLog`. Routing it through+ // the composed view would turn "MortalLoom is on but has no bodyEntries key" into+ // a non-null empty log and stop the fall-through to the local file entirely.const ml = await mlArrayIfEnabled('bodyEntries', { strict });if (ml) return ml.map(({ id, ...rest }) => rest).sort(byDate);- const log = await readJSONFile(DAILY_LOG_FILE, { entries: [] }, { strict });- if (strict && !Array.isArray(log?.entries)) {- throw new Error(`Health daily log malformed: ${DAILY_LOG_FILE}`);- }+ const log = await readLocalDailyLog({ strict, label: 'Health' });return (log.entries || []).filter(e => e.body && Object.keys(e.body).length > 0).map(e => ({ date: e.date, ...e.body }))diff --git a/server/services/meatspaceHealth.test.js b/server/services/meatspaceHealth.test.jsindex 559c058268..3d00a5a4a3 100644--- a/server/services/meatspaceHealth.test.js+++ b/server/services/meatspaceHealth.test.js@@ -40,6 +40,10 @@ vi.mock('../lib/fileUtils.js', () => ({vi.mock('./mortalLoomStore.js', () => ({isMortalLoomEnabled: vi.fn().mockResolvedValue(false),mlArrayIfEnabled: vi.fn().mockResolvedValue(null),+ // meatspaceHealth reaches daily-log.json through the shared reader (#4112), which+ // imports this export even though the body-history path never calls it — a mock+ // factory that omits it would throw on the first access if that ever changes.+ readDailyLogIfEnabled: vi.fn().mockResolvedValue(null),mlPush: vi.fn(),mlPatchById: vi.fn(),mlRemoveById: vi.fn(),diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.jsindex 3a859d1127..a43a3612c7 100644--- a/server/services/meatspaceNicotine.js+++ b/server/services/meatspaceNicotine.js@@ -7,9 +7,9 @@import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';+import { DAILY_LOG_FILE, loadMeatspaceDailyLog } from './meatspaceDailyLog.js';import {isMortalLoomEnabled,- readDailyLogIfEnabled,mlPush,mlPatchById,mlRemoveById,@@ -17,7 +17,6 @@ import {} from './mortalLoomStore.js';const MEATSPACE_DIR = PATHS.meatspace;-const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');const CUSTOM_PRODUCTS_FILE = join(MEATSPACE_DIR, 'custom-nicotine-products.json');const DEFAULT_PRODUCTS = [@@ -104,20 +103,7 @@ function recalcDayTotal(entry) {* default so the UI keeps degrading gracefully; the health-logging COUNT opts in,* because a fake 0 there reads as "you have never logged anything" (#2726).*/-async function loadDailyLog({ strict = false } = {}) {- const ml = await readDailyLogIfEnabled({ strict });- if (ml) return ml;- const raw = await readJSONFile(DAILY_LOG_FILE, { entries: [], lastEntryDate: null }, { allowArray: false, strict });- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {- if (strict) throw new Error(`Nicotine daily log malformed: ${DAILY_LOG_FILE}`);- return { entries: [], lastEntryDate: null };- }- if (!Array.isArray(raw.entries)) {- if (strict) throw new Error(`Nicotine daily log malformed: ${DAILY_LOG_FILE}`);- raw.entries = [];- }- return raw;-}+const loadDailyLog = (options) => loadMeatspaceDailyLog({ ...options, label: 'Nicotine' });async function saveDailyLog(log) {await ensureDir(MEATSPACE_DIR);