Skip to content

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

fix MortalLoom iCloud write failure when the data file has been offloaded

[._.]/ Adam Eivya1a4e0b63085
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7d1560e2c1..3123da2001 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,8 @@
## Fixed
+- **MortalLoom iCloud writes no longer fail when the data file has been offloaded** — under macOS "Optimize Mac Storage," iCloud can evict `MortalLoom.json` to the cloud (a dataless placeholder) hours after PortOS booted. A write would then fail to read the evicted file within the brief retry window and refuse to overwrite it ("MortalLoom store is unreadable; refusing to overwrite") rather than risk truncating your data — but that also blocked the write entirely. PortOS now pre-warms the file on demand: before refusing, it runs `brctl download` and waits for the file to materialize, then re-reads and proceeds. It also detects a legacy `.icloud` placeholder shadowing the real path so it won't seed a fresh (empty) store on top of evicted data. If the file is genuinely corrupt, or the device is offline and can't download it, PortOS still safely refuses rather than clobbering the iCloud copy. The fire-and-forget boot/settings-change pinning remains as the first line of defense.
+
- **[issue-978] Apps no longer get stuck reading "in review" after a no-op idle check** — when the Chief of Staff's idle review picked an app but had nothing to actually do (no claimable plan item, no new commits or PRs to watch), the app could stay marked as under review until a restart or cleanup pass cleared it. Idle checks that find no work now release the app right away while still spacing out how often it's rechecked.
- **[issue-984] Chief of Staff daily action cap holds firm when several jobs come due at once** — scheduled jobs that fired in the same instant could each slip past a small daily action cap before the others were counted, letting the cap be exceeded by one. The cap is now enforced the moment each job is admitted, so simultaneously-due jobs can no longer overshoot it.
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index 27f5c63675..c3015d0a50 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -9,12 +9,13 @@
*/
import { homedir } from 'os';
-import { join } from 'path';
+import { join, dirname, basename } from 'path';
import { readFile, writeFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { randomUUID } from 'crypto';
import { spawn } from 'child_process';
import { safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';
+import { bufferedSpawn } from '../lib/bufferedSpawn.js';
import { isPlainObject } from '../lib/objects.js';
import { getSettings, settingsEvents } from './settings.js';
@@ -152,6 +153,63 @@ function pinAgainstEviction(path) {
});
}
+// === On-demand (blocking) materialization for the write path ===
+
+// macOS' older eviction mechanism renames `Foo.json` to a hidden
+// `.Foo.json.icloud` placeholder, after which `existsSync(Foo.json)` reports
+// false even though real data is sitting there evicted. Detecting the
+// placeholder lets updateStore() refuse to seed a fresh store on top of it
+// (which would shadow the real data) and materialize it instead. Modern macOS
+// uses dataless files (path stays present) so this is belt-and-suspenders, but
+// the silent-data-loss cost if it ever fires is exactly what this module's
+// overwrite guard exists to prevent.
+function icloudPlaceholderPath(path) {
+ return join(dirname(path), `.${basename(path)}.icloud`);
+}
+
+// Unlike the fire-and-forget pinAgainstEviction() at boot, the write path needs
+// to KNOW an evicted file is materialized before deciding whether refusing to
+// overwrite is warranted. `brctl download <path>` materializes a dataless
+// (Optimize-Mac-Storage-evicted) file or an `.icloud` placeholder and exits 0
+// once the bytes are local; we await that exit (bounded by a timeout) and let
+// the caller re-read. Resolves `true` only on a clean exit-0 — non-darwin,
+// missing brctl, spawn error, timeout, and non-zero exit all resolve `false`,
+// every one of which falls through to the caller's existing refuse-to-overwrite
+// guard. So this can only ever recover the situation, never worsen it.
+//
+// Exposed (not const) so tests can drop the timeout without waiting on it.
+export let MATERIALIZE_TIMEOUT_MS = 20000;
+export function _setMaterializeTimeoutForTest(ms) { MATERIALIZE_TIMEOUT_MS = ms; }
+
+// Unlike pinAgainstEviction, this awaits brctl to completion via the shared
+// bufferedSpawn helper (timeout + kill-tree handled there). The timeout bounds a
+// hung download (file evicted AND device offline) so a single write can't block
+// forever. Resolves `true` only on a clean exit-0; every failure mode resolves
+// `false` and falls through to the caller's existing refuse-to-overwrite guard.
+async function materializeNow(path) {
+ if (process.platform !== 'darwin' || !path) return false;
+ const result = await bufferedSpawn('brctl', ['download', path], {
+ timeoutMs: MATERIALIZE_TIMEOUT_MS,
+ shell: false,
+ });
+ if (result.success) return true;
+ if (result.error?.code === 'ENOENT') {
+ // brctl missing — share the dedupe flag with pinAgainstEviction so we
+ // surface the missing-binary warning at most once per process.
+ if (!brctlMissingWarned) {
+ brctlMissingWarned = true;
+ console.warn('⚠️ brctl not found on PATH; MortalLoom on-demand materialize disabled (refuse-to-overwrite guard remains)');
+ }
+ } else if (result.timedOut) {
+ console.warn(`⚠️ brctl download timed out after ${MATERIALIZE_TIMEOUT_MS}ms for MortalLoom store: ${path}`);
+ } else if (result.error) {
+ console.warn(`⚠️ brctl download failed for MortalLoom store: ${result.error.message}`);
+ } else {
+ console.warn(`⚠️ brctl download exited ${result.code} for MortalLoom store: ${path}`);
+ }
+ return false;
+}
+
// Two flags, not one: the listener is durable (sync, idempotent) but the
// initial-pin step does awaits that can reject transiently (settings.json
// read failure). Coupling them under a single `initialized = true` set
@@ -286,27 +344,46 @@ export async function updateStore(mutator) {
// 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);
+ let 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).
+ // (1) file does not exist now (and no `.icloud` placeholder shadows it) →
+ // 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');
+ // (3) the real path is absent but an `.icloud` placeholder is shadowing it
+ // → the file was evicted under the legacy rename mechanism and real
+ // data is sitting there unmaterialized; seeding fresh would bury it.
+ // For (2) and (3) the most common cause on macOS is iCloud eviction
+ // (Optimize-Mac-Storage made the file dataless and the sub-200ms transient
+ // retry isn't long enough to materialize it). Before refusing — which blocks
+ // the user's write — force a BLOCKING `brctl download` and re-read once. This
+ // is the on-demand pre-warm the fire-and-forget boot pin can't guarantee
+ // hours after boot, when the file has been re-evicted under disk pressure.
+ // Only genuinely corrupt JSON / unexpected shapes / offline-evicted files
+ // survive to the throw. Without this guard, the iCloud transient-failure
+ // tolerance in readStoreAtPath would let updateStore silently truncate a
+ // momentarily unreadable iCloud file.
+ const unsafeToSeed = existsSync(path)
+ ? !isPlainObject(store)
+ : existsSync(icloudPlaceholderPath(path));
+ if (unsafeToSeed) {
+ const materialized = await materializeNow(path);
+ if (materialized) {
+ store = await readStoreAtPath(path);
+ console.log(`📥 MortalLoom store materialized from iCloud before write: ${path}`);
+ }
+ if (!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${materialized ? ' even after iCloud materialize' : ''}; 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] = [];
diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.js
index 39891d32c8..0548f58c28 100644
--- a/server/services/mortalLoomStore.test.js
+++ b/server/services/mortalLoomStore.test.js
@@ -165,6 +165,22 @@ describe('mlArrayIfEnabled', () => {
});
describe('updateStore', () => {
+ // updateStore now force-materializes an evicted iCloud file (brctl download)
+ // before refusing to overwrite. These baseline tests assert the refuse/seed
+ // semantics WITHOUT the materialize path interfering, so pin the platform to
+ // linux — materializeNow() short-circuits to `false` off darwin, leaving the
+ // pre-existing guard behavior exactly as it was. The darwin materialize
+ // behavior gets its own describe block below. (process.platform overrides
+ // aren't restored by vi.restoreAllMocks(), so capture+restore explicitly.)
+ let originalPlatformDescriptor;
+ beforeEach(() => {
+ originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
+ });
+ afterEach(() => {
+ if (originalPlatformDescriptor) Object.defineProperty(process, 'platform', originalPlatformDescriptor);
+ });
+
it('seeds a fresh store when the file does not exist', async () => {
existsResult = false;
writeFileMock.mockResolvedValue(undefined);
@@ -225,10 +241,11 @@ describe('updateStore', () => {
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).
+ // (2) post-read check in updateStore's guard → false (file vanished),
+ // (3) `.icloud` placeholder probe → false (no shadowing placeholder).
// The post-read recheck must discriminate this from a transient/corrupt
// case so we don't reject a legitimate seed.
- existsQueue.push(true, false);
+ existsQueue.push(true, false, false);
readFileMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
writeFileMock.mockResolvedValue(undefined);
const result = await store.updateStore((s) => {
@@ -254,6 +271,134 @@ describe('updateStore', () => {
});
});
+describe('updateStore — iCloud on-demand materialize (darwin)', () => {
+ // A fake brctl child shaped for the shared bufferedSpawn helper, which reads
+ // child.stdout/stderr and resolves on the `close` event. Its handler fires
+ // asynchronously with the given exit code; the optional onClose hook lets a
+ // test flip a flag (e.g. "now the file is materialized") atomically with the
+ // close so the post-materialize re-read sees fresh state.
+ const makeMaterializeChild = (exitCode, onClose) => {
+ const noopStream = { on: vi.fn() };
+ const child = {
+ stdout: noopStream,
+ stderr: noopStream,
+ pid: 4242,
+ on: vi.fn(function (evt, cb) {
+ if (evt === 'close') setTimeout(() => { onClose?.(); cb(exitCode, null); }, 0);
+ return child;
+ }),
+ kill: vi.fn(),
+ unref: vi.fn(),
+ };
+ return child;
+ };
+
+ let originalPlatformDescriptor;
+ let originalTimeout;
+ beforeEach(() => {
+ originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ originalTimeout = store.MATERIALIZE_TIMEOUT_MS;
+ store._setMaterializeTimeoutForTest(50);
+ store._resetMortalLoomInitForTest(); // clears brctlMissingWarned dedupe
+ writeFileMock.mockResolvedValue(undefined);
+ });
+ afterEach(() => {
+ if (originalPlatformDescriptor) Object.defineProperty(process, 'platform', originalPlatformDescriptor);
+ store._setMaterializeTimeoutForTest(originalTimeout);
+ });
+
+ it('materializes an evicted dataless file then writes (the reported bug)', async () => {
+ // File exists (dataless placeholder) but reads EAGAIN until brctl download
+ // materializes it. updateStore must recover and write instead of refusing.
+ existsResult = true;
+ const eagain = Object.assign(new Error('EAGAIN'), { code: 'EAGAIN', errno: -11 });
+ let materialized = false;
+ readFileMock.mockImplementation(async () => {
+ if (!materialized) throw eagain;
+ return JSON.stringify({ goals: [{ id: 'existing' }] });
+ });
+ spawnMock.mockReturnValue(makeMaterializeChild(0, () => { materialized = true; }));
+
+ const result = await store.updateStore((s) => {
+ s.goals.push({ id: 'added-after-materialize' });
+ return s.goals.length;
+ });
+
+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.objectContaining({ shell: false }));
+ expect(result).toBe(2);
+ expect(writeFileMock).toHaveBeenCalledTimes(1);
+ const written = JSON.parse(writeFileMock.mock.calls[0][1]);
+ expect(written.goals).toEqual([{ id: 'existing' }, { id: 'added-after-materialize' }]);
+ });
+
+ it('still refuses when brctl exits non-zero (offline/evicted, materialize failed)', async () => {
+ existsResult = true;
+ readFileMock.mockRejectedValue(Object.assign(new Error('EAGAIN'), { code: 'EAGAIN', errno: -11 }));
+ spawnMock.mockReturnValue(makeMaterializeChild(1));
+
+ await expect(
+ store.updateStore((s) => { s.goals.push({ id: 'should-not-write' }); })
+ ).rejects.toThrow(/unreadable; refusing to overwrite/);
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ expect(writeFileMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses with an "even after materialize" diagnostic when JSON is still corrupt post-download', async () => {
+ // brctl succeeds (file materialized) but the bytes are genuinely corrupt —
+ // not an eviction problem. Refuse, and make the log distinguish this from
+ // the never-materialized case.
+ existsResult = true;
+ readFileMock.mockResolvedValue('{ truncated json');
+ spawnMock.mockReturnValue(makeMaterializeChild(0));
+
+ await expect(
+ store.updateStore((s) => { s.goals.push({ id: 'should-not-write' }); })
+ ).rejects.toThrow(/unreadable; refusing to overwrite/);
+ expect(writeFileMock).not.toHaveBeenCalled();
+ expect(console.error).toHaveBeenCalledWith(
+ expect.stringContaining('even after iCloud materialize')
+ );
+ });
+
+ it('materializes an `.icloud` placeholder shadowing the real path instead of seeding fresh', async () => {
+ // Legacy eviction renamed MortalLoom.json → .MortalLoom.json.icloud, so the
+ // real path reads absent. Seeding a fresh store would bury real data — we
+ // must download the placeholder and write the recovered store instead.
+ // existsSync order: (1) readStoreAtPath path=false, (2) ternary path=false,
+ // (3) placeholder=true, (4) post-materialize re-read path=true.
+ existsQueue.push(false, false, true, true);
+ let materialized = false;
+ readFileMock.mockImplementation(async () => {
+ if (!materialized) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
+ return JSON.stringify({ goals: [{ id: 'recovered' }] });
+ });
+ spawnMock.mockReturnValue(makeMaterializeChild(0, () => { materialized = true; }));
+
+ const result = await store.updateStore((s) => {
+ s.goals.push({ id: 'added' });
+ return s.goals.length;
+ });
+
+ // brctl is asked to download the REAL path, not the placeholder.
+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.objectContaining({ shell: false }));
+ expect(result).toBe(2);
+ expect(writeFileMock).toHaveBeenCalledTimes(1);
+ const written = JSON.parse(writeFileMock.mock.calls[0][1]);
+ expect(written.goals).toEqual([{ id: 'recovered' }, { id: 'added' }]);
+ });
+
+ it('does not materialize (no spawn) when seeding a genuinely new file', async () => {
+ // No real file and no placeholder — a first-ever write. Must seed without
+ // paying a brctl download.
+ existsResult = false;
+ const result = await store.updateStore((s) => { s.goals.push({ id: 'first' }); return 'ok'; });
+ expect(result).toBe('ok');
+ expect(spawnMock).not.toHaveBeenCalled();
+ expect(writeFileMock).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('getStatus', () => {
it('returns exists:false when file is missing', async () => {
existsResult = false;