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(mortalloom): gracefully handle transient iCloud read failures
Adam Eivybfec9f79063f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b0c8f9ebd1..a54b280f12 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,3 +20,4 @@- Auto-run the world → universe data rename on server boot. The conversion previously shipped as a manual CLI script (`server/scripts/migrateWorldToUniverse.js`) that nobody knew to invoke, so installs upgrading from the World Builder era kept stale `data/world-builder.json` files and never saw their worlds appear as universes. The new migration `031-world-to-universe-data-rename.js` does the file rename, top-level key rename (`worlds`→`universes`), `worldId`→`universeId` rewrite in `pipeline-series.json`, `worldRun`→`universeRun` rewrite in `media-jobs.json`, and also relinks any `"World: <name>"` render collections in `media-collections.json` to their universe by canonical-name match.- Universe Builder picker dropdown rendered beneath the tab subnav and downstream section cards in Lumen Glass / Blueprint Ops themes. Those themes ship a non-`none` `--port-backdrop-filter`, and the global rule in `index.css` applies it to every `.bg-port-card.border.rounded*` — which turns each such card into its own stacking context. The picker's `absolute z-30` dropdown was trapped inside the header card's context and couldn't paint over later sibling cards. Adding `relative z-30` to the picker's `<header>` lets that stacking context win against subsequent siblings so the dropdown overlays them as intended.- TUI agent raw-PTY buffer no longer truncates the head at ~640KB ("⚠️ raw PTY buffer exceeded 1MB — head dropped"). The buffer feeds `analyzeAgentFailure` at finalize, so silently slicing the head was the exact behavior the warning admitted to ("failure analysis may miss earlier symptoms"). `server/services/agentTuiSpawning.js` now spools raw PTY bytes to a per-agent `raw.txt` file in 250ms-debounced batches (mirroring the existing parsed-output pipeline that writes `output.txt`), so the in-memory footprint stays bounded regardless of run length. `analyzeAgentFailure` reads the **tail** of the file (last 1MB) on failure via a non-throwing `readFileTail` helper; successful runs skip the read entirely. The paste-marker poll keeps only a short-lived post-paste accumulator that lives for the paste window. A 256MB disk safety valve truncates `raw.txt` if a runaway agent exceeds the cap (preserves the most-recent bytes that `readFileTail` actually consumes; warns once and sets a `rawSpoolTruncated` agent-metadata flag). The old `rawBufferTruncated` flag is gone with the in-memory truncation logic.+- `GET /api/digital-twin/identity/goals` (and any other identity read that consults MortalLoom iCloud sync) 500'd with `Unknown system error -11, read` when the MortalLoom.json file in the iCloud ubiquity container was momentarily unreadable — typically while iCloud was mid-sync, downloading, or resolving a conflict. `readStore()` and `getStatus()` in `server/services/mortalLoomStore.js` now catch the transient `readFile`/`stat` failure, log a single warning with the errno, and return `null` / a null-summary response (matching the existing "file not present yet" path). ENOENT races between `existsSync` and `readFile`/`stat` (file disappears mid-call) are treated as silently absent rather than transient — no warning noise, and `getStatus()` reports `exists:false` instead of falsely reporting `exists:true,size:0`. `updateStore()` resolves the path once and threads it through both the read and the write so a settings change mid-call can't desync the overwrite guard from the actual write target; it also refuses to overwrite when the parsed store isn't a plain object (array/primitive) so `JSON.stringify` can't silently drop named properties. Read consumers (`mlArrayIfEnabled`, `mlGetProfileIfEnabled`, `readDailyLogIfEnabled`, `mlIdAtDateIndex`) already handled `null` as "fall through to local PortOS data," so the goals endpoint now serves local data instead of 500ing.diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsindex 8bd2545fe5..3c381d473f 100644--- a/server/services/mortalLoomStore.js+++ b/server/services/mortalLoomStore.js@@ -45,23 +45,78 @@ export async function isMortalLoomEnabled() {return Boolean(s?.mortalloom?.enabled);}-export async function readStore() {- const path = await resolvePath();+/**+ * 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.+ */+async function readStoreAtPath(path) {if (!existsSync(path)) return null;- const raw = await readFile(path, 'utf-8');- return safeJSONParse(raw, null, { context: path });+ const raw = await readFile(path, 'utf-8').catch((err) => {+ // existsSync→readFile race: file disappeared between the two calls.+ // Treat as "absent" silently — no warning noise.+ if (err.code === 'ENOENT') return null;+ console.warn(`⚠️ MortalLoom store unavailable (${err.code || err.errno || 'unknown'}): ${path}`);+ return null;+ });+ if (raw === null) return null;+ const parsed = safeJSONParse(raw, null, { context: path });+ return isPlainObject(parsed) ? parsed : null;+}++export async function readStore() {+ return readStoreAtPath(await resolvePath());}-async function writeStore(data) {- await writeFile(await resolvePath(), JSON.stringify(data, null, 2));+async function writeStoreAtPath(path, data) {+ await writeFile(path, JSON.stringify(data, null, 2));}/** Atomic read → mutate → write. Ensures all array keys are initialized. */export async function updateStore(mutator) {- const store = (await readStore()) || {};- for (const k of ARRAY_KEYS) if (!Array.isArray(store[k])) store[k] = [];- const result = await mutator(store);- await writeStore(store);+ // Resolve the path once and pass it through to both read and write — settings+ // could change mid-call, so we'd otherwise risk reading from one path and+ // writing to another (or the overwrite-guard's existsSync looking at a+ // different file than the read).+ const path = await resolvePath();+ const store = await readStoreAtPath(path);+ // The overwrite guard is based solely on post-read state, not a pre-read+ // snapshot. readStoreAtPath returns null for four reasons; we only care+ // about the *currently observable* state when deciding whether it's safe+ // to write:+ // (1) file does not exist now → safe to seed a fresh store (whether it+ // was absent the whole time, disappeared mid-call, or never appeared+ // in the first place).+ // (2) file exists now but parsed to a non-plain-object value → unreadable+ // (transient iCloud read failure, corrupt JSON, or unexpected shape+ // like a top-level array which JSON.stringify would silently drop).+ // Refuse to overwrite the user's iCloud data.+ // Without this guard, the iCloud transient-failure tolerance in+ // readStoreAtPath would let updateStore silently truncate a momentarily+ // unreadable iCloud file.+ if (existsSync(path) && !isPlainObject(store)) {+ // Log the resolved path server-side for diagnostics; keep the thrown+ // message path-free so it doesn't get echoed back to the UI (route+ // errors serialize as `error: error.message`).+ console.error(`❌ MortalLoom store at ${path} is unreadable; refusing to overwrite`);+ throw new Error('MortalLoom store is unreadable; refusing to overwrite');+ }+ const base = store || {};+ for (const k of ARRAY_KEYS) if (!Array.isArray(base[k])) base[k] = [];+ const result = await mutator(base);+ await writeStoreAtPath(path, base);return result;}@@ -213,18 +268,44 @@ export async function getStatus() {const s = await getSettings();const path = s?.mortalloom?.path?.trim() || DEFAULT_ICLOUD_PATH;const enabled = Boolean(s?.mortalloom?.enabled);- const exists = existsSync(path);- if (!exists) {- return { enabled, path, usingDefault: path === DEFAULT_ICLOUD_PATH, defaultPath: DEFAULT_ICLOUD_PATH,- exists: false, size: 0, mtime: null, summary: null, appStoreUrl: MORTALLOOM_APP_STORE_URL };- }- const st = await stat(path);- const data = safeJSONParse(await readFile(path, 'utf-8'), null);+ const missingResponse = {+ enabled, path, usingDefault: path === DEFAULT_ICLOUD_PATH, defaultPath: DEFAULT_ICLOUD_PATH,+ exists: false, size: 0, mtime: null, summary: null, appStoreUrl: MORTALLOOM_APP_STORE_URL,+ };+ if (!existsSync(path)) return missingResponse;+ // Same transient-iCloud-failure tolerance as readStoreAtPath() — surface a+ // null summary instead of 500ing the Settings status page. ENOENT (file+ // disappeared between existsSync and stat/readFile) collapses back to the+ // "missing" response; only genuinely transient errors keep `exists:true`.+ let statTransient = false;+ const st = await stat(path).catch((err) => {+ if (err.code === 'ENOENT') return null;+ statTransient = true;+ console.warn(`⚠️ MortalLoom status stat unavailable (${err.code || err.errno || 'unknown'}): ${path}`);+ return null;+ });+ if (!st && !statTransient) return missingResponse;+ let readEnoent = false;+ const raw = st ? await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') { readEnoent = true; return null; }+ console.warn(`⚠️ MortalLoom status read unavailable (${err.code || err.errno || 'unknown'}): ${path}`);+ return null;+ }) : null;+ // readFile ENOENT after a successful stat means the file was deleted/moved+ // between the two calls — collapse to the missing response so the endpoint+ // doesn't advertise a phantom file with stale stat metadata.+ if (readEnoent) return missingResponse;+ const parsed = raw === null ? null : safeJSONParse(raw, null);+ // Only compute a summary when the top-level JSON is a plain `{…}` shape.+ // An unexpected top-level array would otherwise pass `typeof === 'object'`+ // and we'd render a misleading 0-count summary instead of `null` (which+ // the UI distinguishes as "store unavailable").+ const data = isPlainObject(parsed) ? parsed : null;const count = k => Array.isArray(data?.[k]) ? data[k].length : 0;return {enabled, path, usingDefault: path === DEFAULT_ICLOUD_PATH, defaultPath: DEFAULT_ICLOUD_PATH,- exists: true, size: st.size, mtime: st.mtime.toISOString(),- summary: data && typeof data === 'object' ? {+ exists: true, size: st?.size ?? 0, mtime: st?.mtime?.toISOString() ?? null,+ summary: data ? {goals: count('goals'),alcoholDrinks: count('alcoholDrinks'),nicotineEntries: count('nicotineEntries'),diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.jsnew file mode 100644index 0000000000..804f630062--- /dev/null+++ b/server/services/mortalLoomStore.test.js@@ -0,0 +1,304 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++let existsResult = true;+// Queue of return values for sequential existsSync() calls. When empty, falls+// back to `existsResult`. Used to simulate ENOENT races where the file exists+// at the first check but disappears before the second.+const existsQueue = [];+const readFileMock = vi.fn();+const statMock = vi.fn();+const writeFileMock = vi.fn();++vi.mock('fs', () => ({+ existsSync: vi.fn(() => (existsQueue.length ? existsQueue.shift() : existsResult)),+}));++vi.mock('fs/promises', () => ({+ readFile: (...args) => readFileMock(...args),+ writeFile: (...args) => writeFileMock(...args),+ stat: (...args) => statMock(...args),+}));++let settings = { mortalloom: { enabled: true } };+vi.mock('./settings.js', () => ({+ getSettings: vi.fn(async () => settings),+}));++vi.mock('../lib/fileUtils.js', () => ({+ safeJSONParse: vi.fn((raw, fallback) => {+ if (typeof raw !== 'string' || !raw) return fallback;+ try { return JSON.parse(raw); } catch { return fallback; }+ }),+ readJSONFile: vi.fn(async () => null),+ dataPath: (...segs) => `/mock/data/${segs.join('/')}`,+ ensureDir: vi.fn(async () => {}),+}));++vi.mock('../lib/objects.js', () => ({+ isPlainObject: (v) => typeof v === 'object' && v !== null && !Array.isArray(v),+}));++const store = await import('./mortalLoomStore.js');++beforeEach(() => {+ existsResult = true;+ existsQueue.length = 0;+ readFileMock.mockReset();+ statMock.mockReset();+ writeFileMock.mockReset();+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+});++afterEach(() => {+ // Restore every spy so the console.warn replacement above doesn't leak+ // into other test files (Vitest doesn't restoreMocks by default here).+ vi.restoreAllMocks();+});++describe('readStore', () => {+ it('returns null when file does not exist', async () => {+ existsResult = false;+ const result = await store.readStore();+ expect(result).toBeNull();+ expect(readFileMock).not.toHaveBeenCalled();+ });++ it('returns parsed data on success', async () => {+ readFileMock.mockResolvedValue(JSON.stringify({ goals: [{ id: 'g1' }] }));+ const result = await store.readStore();+ expect(result).toEqual({ goals: [{ id: 'g1' }] });+ });++ it('returns null and logs a warning on EAGAIN read failure', async () => {+ const err = Object.assign(new Error('Unknown system error -11: Unknown system error -11, read'), {+ code: 'EAGAIN',+ errno: -11,+ syscall: 'read',+ });+ readFileMock.mockRejectedValue(err);++ const result = await store.readStore();++ expect(result).toBeNull();+ expect(console.warn).toHaveBeenCalledWith(+ expect.stringContaining('MortalLoom store unavailable (EAGAIN)')+ );+ });++ it('returns null on unknown errno without code', async () => {+ const err = Object.assign(new Error('Unknown system error -11, read'), { errno: -11 });+ readFileMock.mockRejectedValue(err);++ const result = await store.readStore();++ expect(result).toBeNull();+ expect(console.warn).toHaveBeenCalledWith(+ expect.stringContaining('MortalLoom store unavailable (-11)')+ );+ });++ it('does not warn when file disappears between existsSync and readFile (ENOENT race)', async () => {+ const err = Object.assign(new Error('ENOENT: no such file or directory'), { code: 'ENOENT' });+ readFileMock.mockRejectedValue(err);++ const result = await store.readStore();++ expect(result).toBeNull();+ expect(console.warn).not.toHaveBeenCalled();+ });++ it('returns null when the parsed JSON is a top-level array (unexpected shape)', async () => {+ // Every consumer expects { alcoholDrinks: [...], goals: [...], ... }.+ // A bare array slipping through would let callers misread "no fields+ // missing" as "store available," reporting empty counts. Treat as null.+ readFileMock.mockResolvedValue(JSON.stringify([{ id: 'a1' }, { id: 'a2' }]));+ const result = await store.readStore();+ expect(result).toBeNull();+ });++ it('returns null when the parsed JSON is a primitive', async () => {+ readFileMock.mockResolvedValue(JSON.stringify('legacy-string-blob'));+ const result = await store.readStore();+ expect(result).toBeNull();+ });+});++describe('mlArrayIfEnabled', () => {+ it('returns null when sync disabled', async () => {+ settings = { mortalloom: { enabled: false } };+ const result = await store.mlArrayIfEnabled('goals');+ expect(result).toBeNull();+ expect(readFileMock).not.toHaveBeenCalled();+ });++ it('returns null when store read fails transiently (regression: goals endpoint must not 500)', async () => {+ readFileMock.mockRejectedValue(Object.assign(new Error('boom'), { code: 'EAGAIN' }));+ const result = await store.mlArrayIfEnabled('goals');+ expect(result).toBeNull();+ });++ it('returns array when present', async () => {+ readFileMock.mockResolvedValue(JSON.stringify({ goals: [{ id: 'g1' }, { id: 'g2' }] }));+ const result = await store.mlArrayIfEnabled('goals');+ expect(result).toEqual([{ id: 'g1' }, { id: 'g2' }]);+ });+});++describe('updateStore', () => {+ it('seeds a fresh store when the file does not exist', async () => {+ existsResult = false;+ writeFileMock.mockResolvedValue(undefined);+ const result = await store.updateStore((s) => {+ s.goals.push({ id: 'new-1' });+ return s.goals[0];+ });+ expect(result).toEqual({ id: 'new-1' });+ expect(writeFileMock).toHaveBeenCalledTimes(1);+ const written = JSON.parse(writeFileMock.mock.calls[0][1]);+ expect(written.goals).toEqual([{ id: 'new-1' }]);+ });++ it('refuses to overwrite when file exists but read fails (regression: no silent truncation)', async () => {+ existsResult = true;+ readFileMock.mockRejectedValue(Object.assign(new Error('boom'), { code: 'EAGAIN' }));+ writeFileMock.mockResolvedValue(undefined);+ await expect(+ store.updateStore((s) => { s.goals.push({ id: 'should-not-write' }); })+ ).rejects.toThrow(/unreadable; refusing to overwrite/);+ expect(writeFileMock).not.toHaveBeenCalled();+ });++ it('throws a path-free message so route handlers do not leak the iCloud path to clients', async () => {+ existsResult = true;+ readFileMock.mockRejectedValue(Object.assign(new Error('boom'), { code: 'EAGAIN' }));+ writeFileMock.mockResolvedValue(undefined);+ let caught;+ await store.updateStore((s) => { s.goals.push({ id: 'x' }); }).catch((err) => { caught = err; });+ expect(caught).toBeDefined();+ expect(caught.message).not.toContain('/icloud/MortalLoom.json');+ expect(caught.message).not.toContain('/');+ // The full path still goes to server logs for diagnostics.+ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('/icloud/MortalLoom.json')+ );+ });++ it('refuses to overwrite when file exists but JSON is corrupt', async () => {+ existsResult = true;+ readFileMock.mockResolvedValue('{not json');+ writeFileMock.mockResolvedValue(undefined);+ await expect(+ store.updateStore((s) => { s.goals.push({ id: 'should-not-write' }); })+ ).rejects.toThrow(/unreadable; refusing to overwrite/);+ expect(writeFileMock).not.toHaveBeenCalled();+ });++ it('refuses to overwrite when file parses as an array (truncation guard)', async () => {+ existsResult = true;+ readFileMock.mockResolvedValue(JSON.stringify(['unexpected', 'array', 'shape']));+ writeFileMock.mockResolvedValue(undefined);+ await expect(+ store.updateStore((s) => { s.goals.push({ id: 'should-not-write' }); })+ ).rejects.toThrow(/unreadable; refusing to overwrite/);+ expect(writeFileMock).not.toHaveBeenCalled();+ });++ it('seeds a fresh store when the file disappears between existsSync and read (ENOENT race)', async () => {+ // existsSync sequence: (1) inside readStoreAtPath → true (read attempted),+ // (2) post-read check in updateStore's guard → false (file vanished).+ // The post-read recheck must discriminate this from a transient/corrupt+ // case so we don't reject a legitimate seed.+ existsQueue.push(true, false);+ readFileMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));+ writeFileMock.mockResolvedValue(undefined);+ const result = await store.updateStore((s) => {+ s.goals.push({ id: 'seeded' });+ return s.goals[0];+ });+ expect(result).toEqual({ id: 'seeded' });+ expect(writeFileMock).toHaveBeenCalledTimes(1);+ });++ it('refuses to overwrite when file was absent initially but appears unreadable mid-call (reverse race)', async () => {+ // existsSync sequence: (1) inside readStoreAtPath → false (file absent at+ // the start of the read), (2) post-read check in updateStore's guard →+ // true (iCloud just finished downloading the file). Even though we'd be+ // happy to seed a fresh store, the now-present file's content is unknown,+ // so we must not blindly clobber it.+ existsQueue.push(false, true);+ writeFileMock.mockResolvedValue(undefined);+ await expect(+ store.updateStore((s) => { s.goals.push({ id: 'should-not-write' }); })+ ).rejects.toThrow(/unreadable; refusing to overwrite/);+ expect(writeFileMock).not.toHaveBeenCalled();+ });+});++describe('getStatus', () => {+ it('returns exists:false when file is missing', async () => {+ existsResult = false;+ const status = await store.getStatus();+ expect(status.exists).toBe(false);+ expect(status.size).toBe(0);+ expect(status.summary).toBeNull();+ });++ it('survives a transient stat/read failure with null summary and logs a warning', async () => {+ statMock.mockRejectedValue(Object.assign(new Error('boom'), { code: 'EAGAIN' }));+ const status = await store.getStatus();+ expect(status.exists).toBe(true);+ expect(status.size).toBe(0);+ expect(status.mtime).toBeNull();+ expect(status.summary).toBeNull();+ expect(console.warn).toHaveBeenCalledWith(+ expect.stringContaining('MortalLoom status stat unavailable (EAGAIN)')+ );+ });++ it('treats ENOENT during stat (file deleted after existsSync) as missing, not transient', async () => {+ statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));+ const status = await store.getStatus();+ expect(status.exists).toBe(false);+ expect(status.size).toBe(0);+ expect(status.mtime).toBeNull();+ expect(status.summary).toBeNull();+ expect(console.warn).not.toHaveBeenCalled();+ });++ it('treats ENOENT during readFile (file deleted after successful stat) as missing, not phantom', async () => {+ statMock.mockResolvedValue({ size: 42, mtime: new Date('2026-01-01T00:00:00Z') });+ readFileMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));+ const status = await store.getStatus();+ expect(status.exists).toBe(false);+ expect(status.size).toBe(0);+ expect(status.mtime).toBeNull();+ expect(status.summary).toBeNull();+ expect(console.warn).not.toHaveBeenCalled();+ });++ it('returns null summary when file parses as a top-level array (unexpected shape)', async () => {+ statMock.mockResolvedValue({ size: 16, mtime: new Date('2026-01-01T00:00:00Z') });+ readFileMock.mockResolvedValue(JSON.stringify([{ id: 'a1' }, { id: 'a2' }]));+ const status = await store.getStatus();+ expect(status.exists).toBe(true);+ expect(status.size).toBe(16);+ expect(status.summary).toBeNull();+ });++ it('returns counts when file readable', async () => {+ statMock.mockResolvedValue({ size: 42, mtime: new Date('2026-01-01T00:00:00Z') });+ readFileMock.mockResolvedValue(JSON.stringify({+ goals: [{ id: 'g1' }],+ alcoholDrinks: [{ id: 'a1' }, { id: 'a2' }],+ profile: { biologicalSex: 'm' },+ }));+ const status = await store.getStatus();+ expect(status.exists).toBe(true);+ expect(status.size).toBe(42);+ expect(status.summary.goals).toBe(1);+ expect(status.summary.alcoholDrinks).toBe(2);+ expect(status.summary.hasProfile).toBe(true);+ });+});