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: give MortalLoom reads a sentinel so an unreadable store isn't a fake 0 (#2742)
[._.]/ Adam Eivyc5cad9f88beb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c0d9174ab2..dc6721acce 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -58,6 +58,7 @@- `[issue-2673]` **Your Character level is now your age.** The Character's level is reframed as life experience — `level = floor(age in years)`, derived on read from your canonical birth date instead of being ground out of XP thresholds (JIRA tickets + CoS tasks). XP survives as a cumulative stat but no longer drives level, and the CyberCity HUD badge now shows the age-based level with a progress bar toward your next birthday (a friendly "set birth date" prompt when no birth date is set yet). Existing character records keep loading unchanged, and the derived level is excluded from cross-machine sync so peers never fight over a stale value.- `[issue-2729]` The Character page loads faster the more you've written. Your Wordsmith skill used to be scored by loading every universe you own (plus their entire render history) and rebuilding every Writers Room work with all its drafts, just to count them — so the page got slower with each world and story you added. It now counts them directly in the database, leaving the score itself unchanged.+- `[issue-2742]` On installs that sync health and goals through the MortalLoom iCloud app, an unreadable shared store now correctly shows the Vitalist and Strategist skills (and their metrics) as "Unavailable" instead of a fake level 0. Previously a store that was present-but-unreadable looked identical to "sync turned off", so the read fell through to a local file that had never been written and reported an honest-looking zero — the same fake-0 the rest of the sheet already guards against, one layer deeper.- `[issue-2676]` **Your Character sheet now shows a Metrics grid of your real activity.** Six tiles — POST practice streak, health-logging streak, records created, memories captured, media assets, and goal completion — read straight off the stats each domain already keeps, so the sheet reads like a profile of what you actually do rather than a dice game. They're derived fresh on every page load (never stored, never synced between your machines, and no new activity tracking was added), and they cost nothing extra: the tiles share the same reads that already score your skills. A stat that can't be read says "Unavailable", and a goal completion rate with no goals filed yet says so plainly — neither is ever passed off as a zero.## Creative Commissionsdiff --git a/server/services/characterSkills.test.js b/server/services/characterSkills.test.jsindex fa8009c12e..81625ec4ea 100644--- a/server/services/characterSkills.test.js+++ b/server/services/characterSkills.test.js@@ -11,6 +11,10 @@ import { makePathsProxy } from '../lib/mockPathsDataRoot.js';const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'character-skills-test-'));const MEATSPACE_DIR = join(TEST_DATA_ROOT, 'meatspace');const IDENTITY_DIR = join(TEST_DATA_ROOT, 'digital-twin');+// The MortalLoom shared store the ML-enabled cases in the "real read path" suite+// point settings at. Kept at the temp-root so it survives the per-test MEATSPACE/+// IDENTITY cleanups and is only read when a test flips MortalLoom on.+const MORTALLOOM_FILE = join(TEST_DATA_ROOT, 'MortalLoom.json');vi.mock('../lib/fileUtils.js', async (importOriginal) =>makePathsProxy(await importOriginal(), {@@ -18,11 +22,14 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) =>extraOverrides: () => ({ meatspace: MEATSPACE_DIR, digitalTwin: IDENTITY_DIR }),}));-// MortalLoom gates every health/goals read on settings. Pin it OFF so the loaders-// deterministically fall through to the local files this suite controls — otherwise-// a real settings read decides whether the test exercises the file path at all.+// MortalLoom gates every health/goals read on settings. Default it OFF so the+// loaders deterministically fall through to the local files this suite controls —+// otherwise a real settings read decides whether the test exercises the file path+// at all. Mutable so the "real read path" suite can flip it ON to prove an+// enabled-but-unreadable MortalLoom store reaches `unavailable` (#2742).+const mlSettings = vi.hoisted(() => ({ value: {} }));vi.mock('./settings.js', () => ({- getSettings: () => Promise.resolve({}),+ getSettings: () => Promise.resolve(mlSettings.value),settingsEvents: new EventEmitter(),}));@@ -70,6 +77,7 @@ const rows = (list) => Array.from({ length: list }, (_, i) => ({ id: `r${i}` }))// Restore every stat to the "brand new install" baseline between tests so a test that// populates one domain can't leak into the next one's empty-domain assertions.beforeEach(() => {+ mlSettings.value = {}; // MortalLoom OFF unless a test opts instats.universes = 0;stats.works = 0;stats.catalog = { total: 0, scraps: 0 };@@ -427,6 +435,29 @@ describe('the real read path: an unreadable file is unavailable, an absent one i}));expect(await skillOf('vitalist')).toMatchObject({ value: 2, unavailable: false });});++ // #2742: an enabled-but-unreadable MortalLoom store used to return null exactly+ // like "sync disabled" and fall through to a local health file that, on an+ // ML-backed install, was a genuine ENOENT — scoring a real-looking level 0. The+ // strict read must now surface the unreadable shared store as unavailable.+ it('is unavailable when MortalLoom sync is on but the shared store is unreadable (#2742)', async () => {+ writeFileSync(MORTALLOOM_FILE, '{"bodyEntries": [');+ mlSettings.value = { mortalloom: { enabled: true, path: MORTALLOOM_FILE } };+ expect(await skillOf('vitalist')).toMatchObject({ level: null, value: null, unavailable: true });+ });++ it('counts real health logs from the MortalLoom store when sync is on (#2742)', async () => {+ // Proves the strict read genuinely reaches the shared store — without it, the+ // unavailable case above could pass for an unrelated reason.+ writeFileSync(MORTALLOOM_FILE, JSON.stringify({+ bodyEntries: [+ { id: 'B1', date: '2026-01-01', weightLbs: 180 },+ { id: 'B2', date: '2026-01-02', weightLbs: 181 },+ ],+ }));+ mlSettings.value = { mortalloom: { enabled: true, path: MORTALLOOM_FILE } };+ expect(await skillOf('vitalist')).toMatchObject({ value: 2, unavailable: false });+ });});describe('strategist (goals)', () => {@@ -452,6 +483,24 @@ describe('the real read path: an unreadable file is unavailable, an absent one i}));expect(await skillOf('strategist')).toMatchObject({ value: 3, unavailable: false });});++ // #2742: the goals path probes MortalLoom first (mlArrayIfEnabled('goals')).+ // An enabled-but-unreadable shared store used to be indistinguishable from+ // "sync disabled" and fell through to the local mirror; the strict read must+ // now report the unreadable store as unavailable rather than a fake 0.+ it('is unavailable when MortalLoom sync is on but the shared store is unreadable (#2742)', async () => {+ writeFileSync(MORTALLOOM_FILE, '{"goals": [');+ mlSettings.value = { mortalloom: { enabled: true, path: MORTALLOOM_FILE } };+ expect(await skillOf('strategist')).toMatchObject({ level: null, value: null, unavailable: true });+ });++ it('counts real goal discipline from the MortalLoom store when sync is on (#2742)', async () => {+ writeFileSync(MORTALLOOM_FILE, JSON.stringify({+ goals: [{ id: 'G1', title: 'Example goal', checkIns: [{ id: 'c1' }, { id: 'c2' }], progressHistory: [{ id: 'p1' }] }],+ }));+ mlSettings.value = { mortalloom: { enabled: true, path: MORTALLOOM_FILE } };+ expect(await skillOf('strategist')).toMatchObject({ value: 3, unavailable: false });+ });});it('contains a failure to its own skill — one corrupt file does not blank the sheet', async () => {diff --git a/server/services/identity/store.js b/server/services/identity/store.jsindex 6b552537b2..2983414446 100644--- a/server/services/identity/store.js+++ b/server/services/identity/store.js@@ -108,7 +108,12 @@ export async function loadJSON(filePath, defaultVal, { strict = false } = {}) {// MortalLoom.json; birthDate and lifeExpectancy metadata stay in local PortOS.let mlGoals = null;if (filePath === GOALS_FILE) {- mlGoals = await mlArrayIfEnabled('goals');+ // Forward strict into the ML probe so an enabled-but-unreadable MortalLoom+ // store throws here rather than returning null and falling through to a local+ // file that may be a genuine ENOENT and score a fake 0 (#2742). A readable+ // store with no `goals` key returns null (not a throw) and falls through to+ // the local mirror below — see mlArrayIfEnabled's semantic note.+ mlGoals = await mlArrayIfEnabled('goals', { strict });if (mlGoals) data.goals = mlGoals.map(normalizeGoal);}// Strictness gates on the source that actually supplies the counted array, whichdiff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.jsindex 548c11f4d2..a03846bfc9 100644--- a/server/services/meatspaceAlcohol.js+++ b/server/services/meatspaceAlcohol.js@@ -146,7 +146,7 @@ export function computeRollingAverages(entries, sex = 'male') {* because a fake 0 there reads as "you have never logged anything" (#2726).*/async function loadDailyLog({ strict = false } = {}) {- const ml = await readDailyLogIfEnabled();+ 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)) {diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.jsindex 34d84d21d4..fad49c2bee 100644--- a/server/services/meatspaceHealth.js+++ b/server/services/meatspaceHealth.js@@ -73,7 +73,7 @@ export async function saveBloodTests(data) {* (#2726). Off by default — existing callers keep the empty fallback.*/export async function getBodyHistory({ strict = false } = {}) {- const ml = await mlArrayIfEnabled('bodyEntries');+ 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)) {@@ -236,7 +236,7 @@ export async function addWorkout({ date, type, durationMinutes, intensity, notes* pressure readings (#2726).*/export async function getBloodPressureHistory({ strict = false } = {}) {- const ml = await mlArrayIfEnabled('healthMetrics');+ const ml = await mlArrayIfEnabled('healthMetrics', { strict });const source = ml ?? (await readJSONFile(HEALTH_METRICS_FILE, { entries: [] }, { strict })).entries;if (strict && !Array.isArray(source)) {throw new Error(`Health metrics malformed: ${HEALTH_METRICS_FILE}`);diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.jsindex ad302295d5..3a859d1127 100644--- a/server/services/meatspaceNicotine.js+++ b/server/services/meatspaceNicotine.js@@ -105,7 +105,7 @@ function recalcDayTotal(entry) {* because a fake 0 there reads as "you have never logged anything" (#2726).*/async function loadDailyLog({ strict = false } = {}) {- const ml = await readDailyLogIfEnabled();+ 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)) {diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsindex 6a4bd06c9b..ed5a4517b3 100644--- a/server/services/mortalLoomStore.js+++ b/server/services/mortalLoomStore.js@@ -288,45 +288,87 @@ export async function isMortalLoomEnabled() {* fail window the boot-pin fix guards against (settings rejects transiently* between the two calls) is still live in the read path — first call says* "enabled", second call fails and the helper returns null even though sync- * is on. Returns `null` when sync is disabled OR the read fails.+ * is on.+ *+ * Returns an explicit sentinel `{ enabled, ok, store }` (#2742) instead of a+ * bare store-or-null, because "sync disabled" and "sync enabled but the store+ * is unreadable" are NOT the same answer and callers that count records must be+ * able to tell them apart:+ * - `{ enabled: false, ok: true, store: null }` — sync off. Not a failure;+ * fall through to the local file as always.+ * - `{ enabled: true, ok: true, store: null }` — sync on, store genuinely+ * absent (never written by either device). A trustworthy empty — fall+ * through, same as an ENOENT on a local file.+ * - `{ enabled: true, ok: true, store: {…} }` — sync on, store read.+ * - `{ enabled: true, ok: false, store: null }` — sync on but the store is+ * present-and-unreadable (EACCES/EIO/corrupt JSON/unexpected shape). THIS is+ * the case a strict caller must surface as `unavailable` rather than let it+ * fall through to a possibly-ENOENT local file and score a fake 0 (the #2726+ * fake-0 hole, one layer down — see #2742). `ok` is false ONLY here.*/async function readEnabledStore() {const s = await getSettings();- if (!s?.mortalloom?.enabled) return null;+ if (!s?.mortalloom?.enabled) return { enabled: false, ok: true, store: null };const path = normalizePath(s.mortalloom.path);- if (!path) return null;- return readStoreAtPath(path);+ const { present, ok, store } = await readStoreAtPathResult(path);+ // `ok` collapses "readable" and "genuinely absent" into the single trustworthy+ // answer callers act on; only present-but-unreadable is a failure worth a throw.+ return { enabled: true, ok: ok || !present, store };}/**- * Read + parse the store at `path`. Returns `null` for:- * - file absent (ENOENT or `existsSync` false) — silently- * - any other `readFile` failure (EAGAIN/EDEADLK/EACCES/unknown errno/etc.) —- * with one warn. The intent is iCloud-ubiquity transients (mid-sync,- * downloading, conflict resolution) but the catch is intentionally broad —- * read consumers all treat null as "fall through to local data," and the- * write side has its own overwrite guard, so suppressing a permission /- * unexpected error here just loses the iCloud copy for one cycle, never- * truncates the user's data.- * - corrupt JSON — `safeJSONParse` falls back to null- * - top-level JSON that isn't a plain object (array/string/number/boolean) —- * every consumer treats the store as `{ alcoholDrinks: [...], goals: [...],- * profile: {...}, … }` so an unexpected shape is just as "unavailable" as- * a corrupt file. Returning null keeps callers from misreading an array as- * a successful read and reporting empty counts to the UI.+ * Read + parse the store at `path`, distinguishing absent from unreadable so the+ * strict read path (#2742) can tell a trustworthy empty from a failure. Returns+ * `{ present, ok, store }`:+ * - `{ present: false, ok: true, store: null }` — file absent (ENOENT or+ * `existsSync` false, incl. the existsSync→readFile race). Silent; a genuinely+ * absent store is a trustworthy empty, not a failure.+ * - `{ present: true, ok: false, store: null }` — file present but unreadable:+ * any non-ENOENT `readFile` failure (EAGAIN/EDEADLK/EACCES/unknown errno/etc.,+ * warned once), corrupt JSON, or a top-level shape that isn't a plain object+ * (array/string/number/boolean). Every consumer treats the store as+ * `{ alcoholDrinks: [...], goals: [...], profile: {...}, … }`, so an unexpected+ * shape is just as unavailable as a corrupt file.+ * - `{ present: true, ok: true, store: {…} }` — read + parsed successfully.+ *+ * The broad "any error → unreadable" catch is intentional: non-strict read+ * consumers still treat a null store as "fall through to local data," and the+ * write side has its own overwrite guard, so suppressing a permission /+ * unexpected error here (for those callers) just loses the iCloud copy for one+ * cycle, never truncates the user's data. Strict callers are the ones that turn+ * `ok: false` into an explicit `unavailable`.*/-async function readStoreAtPath(path) {- if (!existsSync(path)) return null;+async function readStoreAtPathResult(path) {+ if (!existsSync(path)) return { present: false, ok: true, store: null };+ let unreadable = false;const raw = await withTransientRetry(() => readFile(path, 'utf-8')).catch((err) => {// existsSync→readFile race: file disappeared between the two calls.- // Treat as "absent" silently — no warning noise.+ // Treat as "absent" silently — no warning noise, no failure.if (err.code === 'ENOENT') return null;console.warn(`⚠️ MortalLoom store unavailable (${err.code || err.errno || 'unknown'}): ${path}`);+ unreadable = true;return null;});- if (raw === null || raw === undefined) return null;+ if (raw === null || raw === undefined) {+ // null + !unreadable is the ENOENT race → absent; null + unreadable is a+ // real read failure that already warned above.+ return unreadable+ ? { present: true, ok: false, store: null }+ : { present: false, ok: true, store: null };+ }const parsed = safeJSONParse(raw, null, { context: path });- return isPlainObject(parsed) ? parsed : null;+ if (!isPlainObject(parsed)) return { present: true, ok: false, store: null };+ return { present: true, ok: true, store: parsed };+}++/**+ * Store object or `null` — the pre-#2742 shape, kept for callers (readStore,+ * updateStore) that only need the parsed store and derive their own+ * absent-vs-unreadable handling (updateStore does its own existsSync ++ * placeholder check for the overwrite guard).+ */+async function readStoreAtPath(path) {+ return (await readStoreAtPathResult(path)).store;}export async function readStore() {@@ -429,7 +471,7 @@ export async function mlReplace(key, array) {/** Returns `store.profile` when MortalLoom sync is enabled, else null. */export async function mlGetProfileIfEnabled() {- const store = await readEnabledStore();+ const { store } = await readEnabledStore();return (store && typeof store.profile === 'object') ? store.profile : null;}@@ -480,7 +522,7 @@ export async function mlUpsertHealthMetricByDate(date, patch) {* 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 readEnabledStore();+ const { store } = await readEnabledStore();if (!store || !Array.isArray(store[key])) return null;const sameDate = store[key].filter(r => r.date === date);return sameDate[index]?.id ?? null;@@ -488,9 +530,30 @@ export async function mlIdAtDateIndex(key, date, index) {// === Read-side convenience ===-/** Returns an array for `key` from the store when enabled, else null (fall through to local). */-export async function mlArrayIfEnabled(key) {- const store = await readEnabledStore();+/**+ * Returns an array for `key` from the store when enabled, else null (fall+ * through to local).+ *+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when sync is+ * enabled but the store is present-and-unreadable, instead of returning null+ * and letting the caller fall through to a local file that may be a genuine+ * ENOENT and score a fake 0 (#2742). Off by default so every existing UI read+ * keeps the swallow-and-fall-through behavior.+ *+ * Semantic note (the question #2742 flagged): when the store is enabled and+ * READABLE but simply has no array for `key` (the user never created records+ * of this kind on either device), we return null and fall through to local+ * even under strict. The store IS the source of truth and we consulted it+ * successfully — a missing key is a legitimate "no such records," and the+ * local file is its mirror, so the local read's own strictness (a genuine+ * ENOENT there is a trustworthy 0) decides the outcome. Only a store we could+ * not READ is a failure.+ */+export async function mlArrayIfEnabled(key, { strict = false } = {}) {+ const { enabled, ok, store } = await readEnabledStore();+ if (strict && enabled && !ok) {+ throw new Error(`MortalLoom store unreadable for key: ${key}`);+ }if (!store || !Array.isArray(store[key])) return null;return store[key];}@@ -526,8 +589,19 @@ export function buildDailyLogFromMortalLoom(store) {return { entries, lastEntryDate: entries.at(-1)?.date || null };}-export async function readDailyLogIfEnabled() {- const store = await readEnabledStore();+/**+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when sync is+ * enabled but the store is present-and-unreadable, instead of returning null+ * and letting the caller fall through to a local daily-log that may be a+ * genuine ENOENT and score a fake 0 (#2742). Off by default. A readable store+ * with no alcohol/nicotine records still returns a real (empty) daily log, not+ * null, so it does not fall through.+ */+export async function readDailyLogIfEnabled({ strict = false } = {}) {+ const { enabled, ok, store } = await readEnabledStore();+ if (strict && enabled && !ok) {+ throw new Error('MortalLoom store unreadable for daily log');+ }return store ? buildDailyLogFromMortalLoom(store) : null;}diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.jsindex ccc1e9b0bc..89ae229056 100644--- a/server/services/mortalLoomStore.test.js+++ b/server/services/mortalLoomStore.test.js@@ -170,6 +170,65 @@ describe('mlArrayIfEnabled', () => {const result = await store.mlArrayIfEnabled('goals');expect(result).toEqual([{ id: 'g1' }, { id: 'g2' }]);});++ // #2742: under strict, "sync disabled" and "sync enabled but store unreadable"+ // must NOT share the null fall-through — the second is a failure a counting+ // caller has to surface as unavailable, not a fake 0.+ describe('strict distinguishes disabled from enabled-but-unreadable (#2742)', () => {+ it('returns null (no throw) when sync is disabled, even under strict', async () => {+ settings = { mortalloom: { enabled: false } };+ await expect(store.mlArrayIfEnabled('goals', { strict: true })).resolves.toBeNull();+ expect(readFileMock).not.toHaveBeenCalled();+ });++ it('returns null (no throw) when the store is genuinely absent, even under strict', async () => {+ existsResult = false; // ENOENT: never written by either device → trustworthy empty+ await expect(store.mlArrayIfEnabled('goals', { strict: true })).resolves.toBeNull();+ expect(readFileMock).not.toHaveBeenCalled();+ });++ it('throws when enabled but the store read fails (EACCES) under strict', async () => {+ readFileMock.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }));+ await expect(store.mlArrayIfEnabled('goals', { strict: true }))+ .rejects.toThrow(/unreadable/i);+ });++ it('throws when enabled but the store is corrupt JSON under strict', async () => {+ readFileMock.mockResolvedValue('{"goals": [');+ await expect(store.mlArrayIfEnabled('goals', { strict: true }))+ .rejects.toThrow(/unreadable/i);+ });++ it('does NOT throw when the store is readable but simply lacks the key (legitimate empty)', async () => {+ // The semantic decision: a readable store with no `goals` array is "no such+ // records," not a failure — fall through to the local mirror as always.+ readFileMock.mockResolvedValue(JSON.stringify({ alcoholDrinks: [] }));+ await expect(store.mlArrayIfEnabled('goals', { strict: true })).resolves.toBeNull();+ });++ it('non-strict swallows an unreadable store (unchanged): returns null', async () => {+ readFileMock.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }));+ await expect(store.mlArrayIfEnabled('goals')).resolves.toBeNull();+ });+ });+});++describe('readDailyLogIfEnabled strict (#2742)', () => {+ it('throws when enabled but the store is unreadable', async () => {+ readFileMock.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }));+ await expect(store.readDailyLogIfEnabled({ strict: true })).rejects.toThrow(/unreadable/i);+ });++ it('non-strict swallows the unreadable store and returns null (unchanged)', async () => {+ readFileMock.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }));+ await expect(store.readDailyLogIfEnabled()).resolves.toBeNull();+ });++ it('returns a real (empty) daily log when the store is readable but has no records', async () => {+ readFileMock.mockResolvedValue(JSON.stringify({ profile: {} }));+ const result = await store.readDailyLogIfEnabled({ strict: true });+ expect(result).toEqual({ entries: [], lastEntryDate: null });+ });});describe('updateStore', () => {