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([issue-3704]): never block on an evicted iCloud file

Adam Eivy53b9c8230cb6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 90a1c5aaea..0f8e031add 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## Stability
+
+- **[issue-3704] The UI no longer goes blank when iCloud offloads a synced file** — macOS "Optimize Mac Storage" can evict MortalLoom and Obsidian files to the cloud. Reading one of those offloaded files used to stall indefinitely, and a handful of stalls was enough to freeze every page in PortOS while the server still looked healthy — pages simply never loaded and only a restart brought them back. PortOS now detects an offloaded file up front, skips the read, asks iCloud to download it in the background, and reports "temporarily unavailable" for just that record until it arrives.
+
## Added
- **Series Autopilot now builds characters before it spends on plot.** A new pre-arc planning stage completes the core cast's causal Ghost → Wound → Lie → Want → Need engines, distinct voices, secrets, relationships, and provisional whole-series transitions before the macro arc is generated. Arc planning then treats those foundations as plot engines: external turns must force character choices rather than inventing a plot and asking late repair passes to retrofit motivation. The existing full-foundation gate remains after the issue-level synopsis plan, where it acts as reconciliation—preserving established identities and adding at most a small number of genuinely story-required characters—so character and story can still change one another without repeatedly rebuilding the expensive arc.
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index 32b77435c1..51ceaefdbd 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -73,6 +73,14 @@ module.exports = {
// agents; fileUtils/resolveInstallRoot also refuse a leaked pin when the
// executing code is itself in a worktree, as belt-and-suspenders.
PORTOS_DATA_ROOT: __dirname,
+ // libuv's filesystem threadpool defaults to FOUR threads, so four slow
+ // or stuck fs operations starve every other fs call in the process —
+ // including the express.static stat/read that serves the UI bundle. An
+ // evicted iCloud file can block a read indefinitely (server/lib/
+ // icloudFile.js guards those reads; this is defense-in-depth, NOT the
+ // fix), and sharp/crypto/dns.lookup draw from the same pool. 16 gives
+ // real headroom at negligible cost — idle threads are just parked.
+ UV_THREADPOOL_SIZE: '16',
PORT: PORTS.API,
PORTOS_HTTP_PORT: PORTS.API_LOCAL, // Loopback HTTP mirror when HTTPS is active
HOST: '0.0.0.0',
diff --git a/server/lib/README.md b/server/lib/README.md
index aa4cd4cb9f..655c1207b5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -148,6 +148,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), `assertSafeFilename(name, {extensions, subject})` (throwing basename/traversal/extension gate) plus its non-throwing twin `isSafeFilename(name, extensions)` for read-only callers that must report a bad stored name as data rather than 400 the request — both share one implementation so the gate and the verdict can't drift, and `isTopLevelEntryName(name)` is that shared traversal half on its own, for callers that can't allowlist extensions (arbitrary user assets, directory entries) but still must refuse separators so no intermediate component is left for a symlink to redirect, `readFileTail(path, maxBytes)` (bounded-memory tail read for append-only logs/spools with no size ceiling — null on error vs `''` for an empty file; shared by the agent-transcript cap, the TUI failure analyzer, and the Codex rollout scan), JSONL append/read/write helpers, dir scans, hashes (`sha256File` streams above 512 KB; `sha256Text` is its in-memory twin for strings/Buffers), JSON helpers. `readJSONFile(path, default)` swallows every failure into `default`; `readJSONFileStrict(path, default)` → `{ ok, value }` (or `readJSONFile(…, { strict: true })`, which throws) tells "absent → trustworthy empty" apart from "present-but-unreadable/corrupt" — use it whenever the result is counted or shown, so a bad read can't report a fake 0. Most paths/file work goes through here. The slashdo command/lib loaders live in `slashdoLoader.js`. |
+| `icloudFile.js` | Guards against blocking reads of **evicted (dataless) iCloud files**. macOS Optimize-Mac-Storage evicts a ubiquity-container file to the cloud; the path and `size` remain but no blocks are local, and the first `read(2)` BLOCKS in the kernel until materialization completes — indefinitely and uncancellably when iCloud is wedged. Four such reads exhaust libuv's 4-thread fs pool and every later `fs` call in the process queues forever, including the `express.static` read that serves the UI bundle (the whole UI hangs while memory-only routes still answer). Retry-on-error can't help: the read doesn't fail, it hangs. `readIfMaterialized(path, {encoding, label})` screens with a `stat()` (safe — never materializes) and rejects with `err.code === ICLOUD_NOT_MATERIALIZED` instead of issuing the read, kicking a background `brctl download` so the next cycle succeeds; concurrent callers for one path share a single read. `isDatalessStats(stats)` is the pure predicate (`size > 0 && blocks === 0`) for callers that already hold a `Stats`; `isSuspectedDataless(path)` is its async form, scoped to darwin + `isUbiquityPath()` so a transparently-compressed ordinary file can't false-positive. `materializeICloudFile(path, {timeoutMs, label})` is the awaited, timeout-bounded `brctl download` for **write** paths that must know the bytes are local before overwriting; `requestMaterialization(path, label)` is the fire-and-forget, per-path-deduped form read paths use. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. |
| `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. |
| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |
| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |
diff --git a/server/lib/icloudFile.js b/server/lib/icloudFile.js
new file mode 100644
index 0000000000..e867d3bd9b
--- /dev/null
+++ b/server/lib/icloudFile.js
@@ -0,0 +1,226 @@
+/**
+ * iCloud (ubiquity-container) file guards.
+ *
+ * ## Why this exists
+ *
+ * macOS "Optimize Mac Storage" evicts iCloud files to the cloud. An evicted
+ * file is *dataless*: the path still exists and `stat()` still reports the real
+ * `size`, but no blocks are allocated locally. The first `read(2)` against it
+ * blocks in the kernel while the OS materializes the bytes — and if that
+ * materialization stalls (wedged `bird` daemon, offline device), **the syscall
+ * never returns and cannot be cancelled**.
+ *
+ * Node's async `fs` calls run on the libuv threadpool, which defaults to FOUR
+ * threads. Four blocked reads therefore exhaust it, and from that moment every
+ * `fs` operation in the process queues forever — including the `express.static`
+ * stat/read that serves the client bundle. The observable symptom is "the whole
+ * UI hangs" while memory-only routes still answer in milliseconds, which reads
+ * like a network fault and is not one. Only a process restart clears it.
+ *
+ * Retry-on-error logic does NOT help here: a dataless read doesn't *fail*, it
+ * *hangs*. The only safe move is to never issue the read in the first place.
+ *
+ * ## The screen
+ *
+ * `stat()` is safe — it does NOT trigger materialization and returns instantly
+ * on a dataless file. Node exposes `Stats.blocks`, so a dataless file is
+ * detectable with no native code and no subprocess: `size > 0 && blocks === 0`.
+ *
+ * The screen is deliberately scoped to darwin AND paths inside a ubiquity
+ * container. An ordinary APFS file can also report `blocks === 0` when it is
+ * transparently compressed (data lives in a `com.apple.decmpfs` xattr), so
+ * applying the screen repo-wide could refuse to read a perfectly good file.
+ * Inside `~/Library/Mobile Documents/` the two coincide in practice — macOS
+ * represents "no local data" *via* the compression mechanism, which is why an
+ * evicted file reports `compressed,dataless` together — and user JSON/markdown
+ * in iCloud Drive is not otherwise compressed by the OS.
+ *
+ * If the screen ever did misfire, the cost is a degraded read (callers surface
+ * "temporarily unavailable" and a background `brctl download` is kicked off,
+ * after which the next read succeeds) — never a truncating write. Callers that
+ * write keep their own refuse-to-overwrite guards.
+ */
+
+import { readFile, stat } from 'fs/promises';
+import { spawn } from 'child_process';
+import { bufferedSpawn } from './bufferedSpawn.js';
+
+/** `err.code` on the rejection `readIfMaterialized` throws for an evicted file. */
+export const ICLOUD_NOT_MATERIALIZED = 'ICLOUD_NOT_MATERIALIZED';
+
+/** Every macOS app ubiquity container lives under this path segment. */
+export const UBIQUITY_MARKER = '/Library/Mobile Documents/';
+
+/** Default bound on an awaited `brctl download` (write paths only). */
+export const DEFAULT_MATERIALIZE_TIMEOUT_MS = 20000;
+
+/** True when `path` sits inside a macOS iCloud ubiquity container. */
+export function isUbiquityPath(path) {
+ return typeof path === 'string' && path.includes(UBIQUITY_MARKER);
+}
+
+/**
+ * True when a `fs.Stats` looks dataless (evicted): a real byte length with zero
+ * blocks allocated locally. Pure, so callers that already hold a `Stats` (e.g. a
+ * status endpoint) can reuse it instead of paying a second `stat()`.
+ */
+export function isDatalessStats(stats) {
+ return Boolean(stats) && stats.size > 0 && stats.blocks === 0;
+}
+
+/**
+ * True when reading `path` would risk a permanently-blocked `read(2)`. Cheap:
+ * one `stat()`, and only on darwin for ubiquity paths. A `stat()` failure
+ * (ENOENT/EACCES) resolves `false` — absent and unreadable are the caller's
+ * existing error paths, not this guard's business.
+ */
+export async function isSuspectedDataless(path) {
+ if (process.platform !== 'darwin' || !isUbiquityPath(path)) return false;
+ const stats = await stat(path).catch(() => null);
+ return isDatalessStats(stats);
+}
+
+// `brctl` is present on every stock macOS. Warn at most once per process if it
+// isn't (sandbox, stripped image) so operators aren't left wondering why
+// materialization is a silent no-op, without spamming on every read.
+let brctlMissingWarned = false;
+
+/** Claim the one-shot "brctl is missing" warning. True on the first call only. */
+export function markBrctlMissing() {
+ if (brctlMissingWarned) return false;
+ brctlMissingWarned = true;
+ return true;
+}
+
+// Dedupe of in-flight background materializations, keyed by path, so repeated
+// reads of the same evicted file don't spawn a `brctl` per request. Cleared when
+// the child fails or exits non-zero so a later read can retry.
+const pendingDownloads = new Set();
+
+/**
+ * Fire-and-forget `brctl download <path>` so an evicted file heals in the
+ * background. Detached + unref'd so a slow download can't keep the process
+ * alive at shutdown. Never throws and never blocks the caller — read paths use
+ * this and then refuse the read for *this* cycle.
+ */
+export function requestMaterialization(path, label = 'iCloud file') {
+ if (process.platform !== 'darwin' || !path) return false;
+ if (pendingDownloads.has(path)) return false;
+ pendingDownloads.add(path);
+
+ // try/catch at a child-process boundary (permitted by the repo's no-try/catch
+ // rule): `spawn` can throw synchronously on resource exhaustion (EMFILE), and
+ // this runs inside a request's read path. A failed *heal* must never replace
+ // the caller's ICLOUD_NOT_MATERIALIZED verdict with a spawn error — the read
+ // is still correctly refused either way.
+ let child;
+ try {
+ child = spawn('brctl', ['download', path], { detached: true, stdio: 'ignore' });
+ child.unref();
+ } catch (err) {
+ pendingDownloads.delete(path);
+ console.warn(`⚠️ could not spawn brctl download for ${label}: ${err.message}`);
+ return false;
+ }
+ // Capture `path` in each handler so a late exit from one child can't clear the
+ // dedupe entry for a different path.
+ child.on('error', (err) => {
+ pendingDownloads.delete(path);
+ if (err.code === 'ENOENT') {
+ if (markBrctlMissing()) {
+ console.warn(`⚠️ brctl not found on PATH; ${label} materialization disabled`);
+ }
+ return;
+ }
+ console.warn(`⚠️ brctl download failed for ${label}: ${err.message}`);
+ });
+ child.on('exit', (code, signal) => {
+ pendingDownloads.delete(path);
+ if (code === 0) {
+ console.log(`📥 ${label} materialized from iCloud: ${path}`);
+ } else if (code !== null) {
+ console.warn(`⚠️ brctl download exited ${code} for ${label}: ${path}`);
+ } else {
+ console.warn(`⚠️ brctl download killed by ${signal} for ${label}: ${path}`);
+ }
+ });
+ return true;
+}
+
+/**
+ * Awaited `brctl download <path>`, bounded by `timeoutMs`. For **write** paths
+ * that must know whether the bytes are local before deciding it's safe to
+ * overwrite. Resolves `true` only on a clean exit-0; every failure mode
+ * (non-darwin, missing brctl, spawn error, timeout, non-zero exit) resolves
+ * `false` so the caller falls through to its own refuse-to-overwrite guard —
+ * this can only improve the situation, never worsen it.
+ *
+ * Read paths must NOT use this: a wedged iCloud makes every read pay the full
+ * timeout. They use `requestMaterialization` (background) instead.
+ */
+export async function materializeICloudFile(path, options = {}) {
+ const { timeoutMs = DEFAULT_MATERIALIZE_TIMEOUT_MS, label = 'iCloud file' } = options;
+ if (process.platform !== 'darwin' || !path) return false;
+ const result = await bufferedSpawn('brctl', ['download', path], { timeoutMs, shell: false });
+ if (result.success) return true;
+ if (result.error?.code === 'ENOENT') {
+ if (markBrctlMissing()) {
+ console.warn(`⚠️ brctl not found on PATH; ${label} on-demand materialize disabled`);
+ }
+ } else if (result.timedOut) {
+ console.warn(`⚠️ brctl download timed out after ${timeoutMs}ms for ${label}: ${path}`);
+ } else if (result.error) {
+ console.warn(`⚠️ brctl download failed for ${label}: ${result.error.message}`);
+ } else {
+ console.warn(`⚠️ brctl download exited ${result.code} for ${label}: ${path}`);
+ }
+ return false;
+}
+
+// Single-flight map so N concurrent callers for the same path share ONE
+// underlying read and can occupy at most one threadpool slot between them.
+// Entries are removed as soon as the read settles, so a later call re-reads
+// (this coalesces concurrency, it does not cache content).
+const inFlightReads = new Map();
+
+/**
+ * `readFile`, but never against an evicted iCloud file.
+ *
+ * - Materialized (or not an iCloud path at all): a plain `readFile`.
+ * - Evicted: kicks a background `brctl download` and rejects with
+ * `err.code === ICLOUD_NOT_MATERIALIZED` — the read is never issued, so no
+ * threadpool slot can be stranded.
+ *
+ * Concurrent calls for the same path share one read.
+ *
+ * Residual risk, accepted and bounded: eviction can still land in the window
+ * between the `stat()` screen and the `readFile`. Single-flight caps the damage
+ * at one threadpool slot per path rather than one per caller, and
+ * `UV_THREADPOOL_SIZE` is raised in `ecosystem.config.cjs` so a stranded slot
+ * doesn't starve the process.
+ */
+export async function readIfMaterialized(path, options = {}) {
+ const existing = inFlightReads.get(path);
+ if (existing) return existing;
+ const pending = guardedRead(path, options).finally(() => inFlightReads.delete(path));
+ inFlightReads.set(path, pending);
+ return pending;
+}
+
+async function guardedRead(path, options) {
+ const { encoding = 'utf-8', label = 'iCloud file' } = options;
+ if (await isSuspectedDataless(path)) {
+ requestMaterialization(path, label);
+ const err = new Error(`${label} is evicted from local storage (iCloud); refusing to block on read`);
+ err.code = ICLOUD_NOT_MATERIALIZED;
+ throw err;
+ }
+ return readFile(path, encoding);
+}
+
+/** Test hook: clear the one-shot warning + dedupe/single-flight state. */
+export function _resetICloudFileStateForTest() {
+ brctlMissingWarned = false;
+ pendingDownloads.clear();
+ inFlightReads.clear();
+}
diff --git a/server/lib/icloudFile.test.js b/server/lib/icloudFile.test.js
new file mode 100644
index 0000000000..7fc44664da
--- /dev/null
+++ b/server/lib/icloudFile.test.js
@@ -0,0 +1,303 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// `stat`/`readFile` are mocked so a dataless file can be simulated on any
+// platform (an evicted iCloud file cannot be created in a test), and so the
+// suite can assert that the guarded read never issues `readFile` at all.
+const statMock = vi.fn();
+const readFileMock = vi.fn();
+const spawnMock = vi.fn();
+const bufferedSpawnMock = vi.fn();
+
+vi.mock('fs/promises', () => ({
+ stat: (...args) => statMock(...args),
+ readFile: (...args) => readFileMock(...args),
+}));
+
+vi.mock('child_process', () => ({
+ spawn: (...args) => spawnMock(...args),
+}));
+
+vi.mock('./bufferedSpawn.js', () => ({
+ bufferedSpawn: (...args) => bufferedSpawnMock(...args),
+}));
+
+const UBIQUITY_DIR = '/Users/example/Library/Mobile Documents/iCloud~com~example~App/Documents';
+const ICLOUD_PATH = `${UBIQUITY_DIR}/Store.json`;
+const LOCAL_PATH = '/Users/example/projects/app/data/store.json';
+
+// A dataless (evicted) file: real byte length, zero blocks allocated locally.
+const datalessStats = { size: 503098, blocks: 0 };
+const materializedStats = { size: 503098, blocks: 984 };
+
+// A stand-in for the detached `brctl download` child requestMaterialization spawns.
+function makeFakeChild() {
+ const handlers = {};
+ return {
+ unref: vi.fn(),
+ on(event, cb) { handlers[event] = cb; return this; },
+ emit(event, ...args) { handlers[event]?.(...args); },
+ };
+}
+
+let icloud;
+let warnSpy;
+let logSpy;
+let platformSpy;
+
+beforeEach(async () => {
+ vi.resetModules();
+ statMock.mockReset();
+ readFileMock.mockReset();
+ spawnMock.mockReset();
+ bufferedSpawnMock.mockReset();
+ // The guard is macOS-only; pin the platform so the suite is deterministic on
+ // Linux CI as well as a developer Mac.
+ platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ spawnMock.mockReturnValue(makeFakeChild());
+ icloud = await import('./icloudFile.js');
+ icloud._resetICloudFileStateForTest();
+});
+
+afterEach(() => {
+ platformSpy.mockRestore();
+ warnSpy.mockRestore();
+ logSpy.mockRestore();
+});
+
+describe('isUbiquityPath', () => {
+ it('recognizes a ubiquity-container path', () => {
+ expect(icloud.isUbiquityPath(ICLOUD_PATH)).toBe(true);
+ });
+
+ it('rejects an ordinary path and non-strings', () => {
+ expect(icloud.isUbiquityPath(LOCAL_PATH)).toBe(false);
+ expect(icloud.isUbiquityPath(undefined)).toBe(false);
+ expect(icloud.isUbiquityPath(42)).toBe(false);
+ });
+});
+
+describe('isDatalessStats', () => {
+ it('is true only for a non-empty file with zero local blocks', () => {
+ expect(icloud.isDatalessStats(datalessStats)).toBe(true);
+ expect(icloud.isDatalessStats(materializedStats)).toBe(false);
+ });
+
+ it('is false for a genuinely empty file (size 0), not dataless', () => {
+ // A 0-byte file legitimately has 0 blocks — treating it as evicted would
+ // refuse to read a real, readable, empty file forever.
+ expect(icloud.isDatalessStats({ size: 0, blocks: 0 })).toBe(false);
+ });
+
+ it('is false for a missing stats object', () => {
+ expect(icloud.isDatalessStats(null)).toBe(false);
+ expect(icloud.isDatalessStats(undefined)).toBe(false);
+ });
+});
+
+describe('isSuspectedDataless', () => {
+ it('screens a dataless ubiquity file', async () => {
+ statMock.mockResolvedValue(datalessStats);
+ await expect(icloud.isSuspectedDataless(ICLOUD_PATH)).resolves.toBe(true);
+ });
+
+ it('does not stat a non-ubiquity path at all', async () => {
+ // An ordinary APFS file can report blocks:0 when transparently compressed,
+ // so the guard must never apply outside a ubiquity container.
+ await expect(icloud.isSuspectedDataless(LOCAL_PATH)).resolves.toBe(false);
+ expect(statMock).not.toHaveBeenCalled();
+ });
+
+ it('is inert off darwin', async () => {
+ platformSpy.mockReturnValue('linux');
+ await expect(icloud.isSuspectedDataless(ICLOUD_PATH)).resolves.toBe(false);
+ expect(statMock).not.toHaveBeenCalled();
+ });
+
+ it('treats a stat failure as not-dataless (absent/EACCES is the caller\'s path)', async () => {
+ statMock.mockRejectedValue(Object.assign(new Error('nope'), { code: 'ENOENT' }));
+ await expect(icloud.isSuspectedDataless(ICLOUD_PATH)).resolves.toBe(false);
+ });
+});
+
+describe('readIfMaterialized', () => {
+ it('issues ZERO readFile calls against a dataless file', async () => {
+ statMock.mockResolvedValue(datalessStats);
+
+ await expect(icloud.readIfMaterialized(ICLOUD_PATH)).rejects.toMatchObject({
+ code: icloud.ICLOUD_NOT_MATERIALIZED,
+ });
+ // The whole point: the blocking read is never issued.
+ expect(readFileMock).not.toHaveBeenCalled();
+ });
+
+ it('kicks a background brctl download for an evicted file', async () => {
+ statMock.mockResolvedValue(datalessStats);
+
+ await icloud.readIfMaterialized(ICLOUD_PATH).catch(() => {});
+
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'brctl',
+ ['download', ICLOUD_PATH],
+ expect.objectContaining({ detached: true })
+ );
+ });
+
+ it('reads normally when the file is materialized', async () => {
+ statMock.mockResolvedValue(materializedStats);
+ readFileMock.mockResolvedValue('{"ok":true}');
+
+ await expect(icloud.readIfMaterialized(ICLOUD_PATH)).resolves.toBe('{"ok":true}');
+ expect(readFileMock).toHaveBeenCalledWith(ICLOUD_PATH, 'utf-8');
+ });
+
+ it('reads a non-iCloud path without any stat overhead', async () => {
+ readFileMock.mockResolvedValue('local');
+
+ await expect(icloud.readIfMaterialized(LOCAL_PATH)).resolves.toBe('local');
+ expect(statMock).not.toHaveBeenCalled();
+ });
+
+ it('propagates a normal read error unchanged', async () => {
+ statMock.mockResolvedValue(materializedStats);
+ readFileMock.mockRejectedValue(Object.assign(new Error('gone'), { code: 'ENOENT' }));
+
+ await expect(icloud.readIfMaterialized(ICLOUD_PATH)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('coalesces concurrent reads of one path into a single read', async () => {
+ statMock.mockResolvedValue(materializedStats);
+ readFileMock.mockResolvedValue('shared');
+
+ const results = await Promise.all([
+ icloud.readIfMaterialized(ICLOUD_PATH),
+ icloud.readIfMaterialized(ICLOUD_PATH),
+ icloud.readIfMaterialized(ICLOUD_PATH),
+ ]);
+
+ expect(results).toEqual(['shared', 'shared', 'shared']);
+ // Single-flight is what caps threadpool occupancy at one slot per path.
+ expect(readFileMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not cache across settled calls (coalesces concurrency only)', async () => {
+ statMock.mockResolvedValue(materializedStats);
+ readFileMock.mockResolvedValueOnce('first').mockResolvedValueOnce('second');
+
+ await expect(icloud.readIfMaterialized(ICLOUD_PATH)).resolves.toBe('first');
+ await expect(icloud.readIfMaterialized(ICLOUD_PATH)).resolves.toBe('second');
+ expect(readFileMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('shares a rejection with every concurrent caller and then clears', async () => {
+ statMock.mockResolvedValue(datalessStats);
+
+ const settled = await Promise.allSettled([
+ icloud.readIfMaterialized(ICLOUD_PATH),
+ icloud.readIfMaterialized(ICLOUD_PATH),
+ ]);
+ expect(settled.every(r => r.status === 'rejected')).toBe(true);
+ expect(statMock).toHaveBeenCalledTimes(1);
+
+ // The single-flight entry must be released even on rejection, or the path
+ // would be permanently poisoned once iCloud recovers.
+ statMock.mockResolvedValue(materializedStats);
+ readFileMock.mockResolvedValue('healed');
+ await expect(icloud.readIfMaterialized(ICLOUD_PATH)).resolves.toBe('healed');
+ });
+
+ it('does not coalesce distinct paths', async () => {
+ statMock.mockResolvedValue(materializedStats);
+ readFileMock.mockResolvedValue('x');
+
+ await Promise.all([
+ icloud.readIfMaterialized(`${UBIQUITY_DIR}/a.json`),
+ icloud.readIfMaterialized(`${UBIQUITY_DIR}/b.json`),
+ ]);
+
+ expect(readFileMock).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('requestMaterialization', () => {
+ it('dedupes while a download is in flight, and retries after it exits', () => {
+ const child = makeFakeChild();
+ spawnMock.mockReturnValue(child);
+
+ expect(icloud.requestMaterialization(ICLOUD_PATH)).toBe(true);
+ expect(icloud.requestMaterialization(ICLOUD_PATH)).toBe(false);
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+
+ // Once the child exits the dedupe entry clears, so a later read can retry.
+ child.emit('exit', 0, null);
+ expect(icloud.requestMaterialization(ICLOUD_PATH)).toBe(true);
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('unrefs the child so a slow download cannot hold the process open', () => {
+ const child = makeFakeChild();
+ spawnMock.mockReturnValue(child);
+ icloud.requestMaterialization(ICLOUD_PATH);
+ expect(child.unref).toHaveBeenCalled();
+ });
+
+ it('warns once when brctl is missing', () => {
+ const first = makeFakeChild();
+ spawnMock.mockReturnValue(first);
+ icloud.requestMaterialization(`${UBIQUITY_DIR}/a.json`);
+ first.emit('error', Object.assign(new Error('nope'), { code: 'ENOENT' }));
+
+ const second = makeFakeChild();
+ spawnMock.mockReturnValue(second);
+ icloud.requestMaterialization(`${UBIQUITY_DIR}/b.json`);
+ second.emit('error', Object.assign(new Error('nope'), { code: 'ENOENT' }));
+
+ const missingWarns = warnSpy.mock.calls.filter(([m]) => String(m).includes('brctl not found'));
+ expect(missingWarns).toHaveLength(1);
+ });
+
+ it('is a no-op off darwin', () => {
+ platformSpy.mockReturnValue('linux');
+ expect(icloud.requestMaterialization(ICLOUD_PATH)).toBe(false);
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('materializeICloudFile', () => {
+ it('resolves true on a clean brctl exit', async () => {
+ bufferedSpawnMock.mockResolvedValue({ success: true, code: 0 });
+ await expect(icloud.materializeICloudFile(ICLOUD_PATH)).resolves.toBe(true);
+ expect(bufferedSpawnMock).toHaveBeenCalledWith(
+ 'brctl',
+ ['download', ICLOUD_PATH],
+ expect.objectContaining({ shell: false })
+ );
+ });
+
+ it('resolves false (never throws) on a timeout, so the caller keeps its own guard', async () => {
+ bufferedSpawnMock.mockResolvedValue({ success: false, code: -1, timedOut: true });
+ await expect(icloud.materializeICloudFile(ICLOUD_PATH, { timeoutMs: 50 })).resolves.toBe(false);
+ });
+
+ it('resolves false on a non-zero exit', async () => {
+ bufferedSpawnMock.mockResolvedValue({ success: false, code: 1, timedOut: false });
+ await expect(icloud.materializeICloudFile(ICLOUD_PATH)).resolves.toBe(false);
+ });
+
+ it('honors the caller-supplied timeout', async () => {
+ bufferedSpawnMock.mockResolvedValue({ success: true, code: 0 });
+ await icloud.materializeICloudFile(ICLOUD_PATH, { timeoutMs: 1234 });
+ expect(bufferedSpawnMock).toHaveBeenCalledWith(
+ 'brctl',
+ expect.any(Array),
+ expect.objectContaining({ timeoutMs: 1234 })
+ );
+ });
+
+ it('is a no-op off darwin', async () => {
+ platformSpy.mockReturnValue('linux');
+ await expect(icloud.materializeICloudFile(ICLOUD_PATH)).resolves.toBe(false);
+ expect(bufferedSpawnMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 7a1ad9756a..614d05f761 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -148,6 +148,7 @@ export * from './createNewestWinsGuard.js';
export * from './dataRoot.js';
export * from './fileUtils.js';
export * from './fileWriteQueue.js';
+export * from './icloudFile.js';
export * from './spawnCwd.js';
export * from './schemaVersions.js';
export * from './imageClean.js';
diff --git a/server/routes/notes.js b/server/routes/notes.js
index 1ad1158e8c..e906f06a8e 100644
--- a/server/routes/notes.js
+++ b/server/routes/notes.js
@@ -22,7 +22,15 @@ import {
const router = Router();
const NOT_FOUND_CODES = new Set(['VAULT_NOT_FOUND', 'NOTE_NOT_FOUND']);
-const errorStatus = (code) => NOT_FOUND_CODES.has(code) ? 404 : 400;
+// The note exists but iCloud has evicted its bytes — a transient condition that
+// heals once the background `brctl download` completes, so it's 503 (retry me),
+// not 404 (gone) or 400 (your request was wrong).
+const UNAVAILABLE_CODES = new Set(['NOTE_EVICTED']);
+const errorStatus = (code) => {
+ if (NOT_FOUND_CODES.has(code)) return 404;
+ if (UNAVAILABLE_CODES.has(code)) return 503;
+ return 400;
+};
function throwOnError(result, fallbackMessage) {
if (result?.error) {
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index 48af21349b..e9eec32705 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -10,12 +10,13 @@
import { homedir } from 'os';
import { join, dirname, basename } from 'path';
-import { readFile, stat } from 'fs/promises';
+import { stat } from 'fs/promises';
import { existsSync } from 'fs';
import { randomUUID } from 'crypto';
import { spawn } from 'child_process';
import { atomicWrite, safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';
import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+import { ICLOUD_NOT_MATERIALIZED, isDatalessStats, readIfMaterialized } from '../lib/icloudFile.js';
import { isPlainObject } from '../lib/objects.js';
import { getSettings, settingsEvents } from './settings.js';
@@ -347,7 +348,23 @@ async function readStoreAtPathResult(path) {
// closes the existsSync→readFile TOCTOU where iCloud offloads the file between
// the check and the read. `readFile`'s ENOENT is the ONLY genuine "absent".
let unreadable = false;
- const raw = await withTransientRetry(() => readFile(path, 'utf-8')).catch((err) => {
+ // `readIfMaterialized` — NOT a bare `readFile`. On modern macOS an evicted
+ // (dataless) iCloud file does not fail with EAGAIN the way the retry logic
+ // below assumes; the read BLOCKS forever in the kernel and strands a libuv
+ // threadpool thread, and four of those take the entire server's filesystem
+ // access down with them (see server/lib/icloudFile.js). The guard screens with
+ // a `stat()` — which never materializes — and rejects with
+ // ICLOUD_NOT_MATERIALIZED instead of issuing the read, kicking a background
+ // `brctl download` so the next cycle succeeds.
+ const raw = await withTransientRetry(() => readIfMaterialized(path, { label: 'MortalLoom store' })).catch((err) => {
+ if (err.code === ICLOUD_NOT_MATERIALIZED) {
+ // Present but evicted — never a trustworthy empty. Same classification as
+ // the legacy `.icloud` placeholder case below, so a strict read reports
+ // `unavailable` and updateStore's guard refuses to seed over real data.
+ console.warn(`⚠️ MortalLoom store evicted from local storage; skipping read until iCloud materializes it: ${path}`);
+ unreadable = true;
+ return null;
+ }
if (err.code === 'ENOENT') {
// Genuinely absent — UNLESS a legacy `.MortalLoom.json.icloud` placeholder
// shadows the real path, which means the store EXISTS but is offloaded under
@@ -666,7 +683,17 @@ export async function getStatus() {
});
if (!st && !statTransient) return missingResponse;
let readEnoent = false;
- const raw = st ? await withTransientRetry(() => readFile(path, 'utf-8')).catch((err) => {
+ // An evicted (dataless) store must NOT be read — the read would block forever
+ // and strand a libuv threadpool thread, taking the whole server's filesystem
+ // access down with it (see server/lib/icloudFile.js). Reuse the `stat` we
+ // already have rather than paying a second one. `size`/`mtime` stay accurate
+ // for a dataless file, so the UI still reports a real file with a null
+ // summary — the same "store unavailable" shape it already renders.
+ const evicted = Boolean(st) && isDatalessStats(st);
+ if (evicted) {
+ console.warn(`⚠️ MortalLoom store evicted from local storage; status summary unavailable: ${path}`);
+ }
+ const raw = st && !evicted ? await withTransientRetry(() => readIfMaterialized(path, { label: 'MortalLoom store' })).catch((err) => {
if (err.code === 'ENOENT') { readEnoent = true; return null; }
console.warn(`⚠️ MortalLoom status read unavailable (${err.code || err.errno || 'unknown'}): ${path}`);
return null;
diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.js
index 6aa6d63226..6101faa46f 100644
--- a/server/services/mortalLoomStore.test.js
+++ b/server/services/mortalLoomStore.test.js
@@ -940,3 +940,85 @@ describe('initMortalLoomStore — brctl pinning', () => {
}).not.toThrow();
});
});
+
+// =============================================================================
+// Evicted (dataless) iCloud store — #3704
+// =============================================================================
+//
+// Regression cover for the incident where a dataless MortalLoom.json blocked
+// four libuv threadpool threads in an uncancellable read(2) and took the entire
+// UI offline (express.static could no longer serve the client bundle). The fix
+// is in server/lib/icloudFile.js: screen with stat() and refuse the read.
+//
+// These tests use a REAL ubiquity-container path — the guard is deliberately
+// scoped to `/Library/Mobile Documents/` so it can't misfire on the ordinary
+// `/icloud/...` fixture path the rest of this suite uses.
+describe('evicted (dataless) iCloud store', () => {
+ const UBIQUITY_PATH = '/Users/example/Library/Mobile Documents/iCloud~net~example~App/Documents/MortalLoom.json';
+ // Dataless: real byte length, zero blocks allocated locally.
+ const DATALESS_STATS = { size: 503098, blocks: 0, mtime: new Date('2026-08-08T14:35:00Z') };
+ let platformSpy;
+
+ function fakeBrctlChild() {
+ const handlers = {};
+ return {
+ unref: vi.fn(),
+ on(event, cb) { handlers[event] = cb; return this; },
+ emit(event, ...args) { handlers[event]?.(...args); },
+ };
+ }
+
+ beforeEach(async () => {
+ platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');
+ settings = { mortalloom: { enabled: true, path: UBIQUITY_PATH } };
+ statMock.mockResolvedValue(DATALESS_STATS);
+ spawnMock.mockReturnValue(fakeBrctlChild());
+ const icloud = await import('../lib/icloudFile.js');
+ icloud._resetICloudFileStateForTest();
+ });
+
+ afterEach(() => platformSpy.mockRestore());
+
+ it('never issues a readFile against the evicted store', async () => {
+ // THE regression assertion: pre-fix this called readFile and (on a real
+ // wedged iCloud) never returned, stranding a threadpool thread forever.
+ await store.readStore();
+ expect(readFileMock).not.toHaveBeenCalled();
+ });
+
+ it('reads as present-but-unreadable, never as a trustworthy empty', async () => {
+ // Classifying an evicted store as "absent" would let a strict read report a
+ // trustworthy 0 (and updateStore seed a fresh store on top of the user's
+ // real, merely-offloaded data). Present-but-unreadable throws instead.
+ await expect(store.mlArrayIfEnabled('goals', { strict: true }))
+ .rejects.toThrow(/unreadable for key: goals/);
+ // A non-strict read of the same state falls through to local data.
+ await expect(store.mlArrayIfEnabled('goals')).resolves.toBeNull();
+ });
+
+ it('kicks a background brctl download so the next read can succeed', async () => {
+ await store.readStore();
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'brctl',
+ ['download', UBIQUITY_PATH],
+ expect.objectContaining({ detached: true })
+ );
+ });
+
+ it('reports the file in getStatus with a null summary, without reading it', async () => {
+ const status = await store.getStatus();
+ expect(status.exists).toBe(true);
+ expect(status.size).toBe(503098);
+ expect(status.summary).toBeNull();
+ expect(readFileMock).not.toHaveBeenCalled();
+ });
+
+ it('reads normally once iCloud materializes the file', async () => {
+ statMock.mockResolvedValue({ size: 40, blocks: 8, mtime: new Date() });
+ readFileMock.mockResolvedValue(JSON.stringify({ goals: [{ id: 'A' }] }));
+
+ const result = await store.readStore();
+ expect(result).toEqual({ goals: [{ id: 'A' }] });
+ expect(readFileMock).toHaveBeenCalledWith(UBIQUITY_PATH, 'utf-8');
+ });
+});
diff --git a/server/services/obsidian.js b/server/services/obsidian.js
index 05fb7f9028..860328ae11 100644
--- a/server/services/obsidian.js
+++ b/server/services/obsidian.js
@@ -6,11 +6,12 @@
* Notes stay in their original vault directories — PortOS indexes but doesn't copy.
*/
-import { readFile, writeFile, readdir, stat, unlink } from 'fs/promises';
+import { writeFile, readdir, stat, unlink } from 'fs/promises';
import { existsSync, realpathSync } from 'fs';
import { join, relative, resolve, basename, dirname, extname, isAbsolute } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { ICLOUD_NOT_MATERIALIZED, readIfMaterialized } from '../lib/icloudFile.js';
const VAULTS_FILE = join(PATHS.brain, 'obsidian-vaults.json');
@@ -142,6 +143,27 @@ export async function detectVaults() {
// NOTE SCANNING & READING
// =============================================================================
+// The default Obsidian vault location is an iCloud ubiquity container
+// (DEFAULT_ICLOUD_OBSIDIAN above), so every note read here can hit a file macOS
+// has evicted to the cloud. A plain `readFile` on an evicted file BLOCKS
+// forever in the kernel and strands a libuv threadpool thread — and a vault
+// walk fires one read per note, so a single evicted vault can exhaust the whole
+// pool and take the server's filesystem access (including the UI bundle) down
+// with it. See server/lib/icloudFile.js.
+//
+// Returns `null` for an evicted note so each caller can skip it and degrade to
+// partial results, rather than failing the whole scan/search. Every other error
+// still propagates unchanged.
+async function readNoteContent(fullPath) {
+ return readIfMaterialized(fullPath, { label: 'Obsidian note' }).catch((err) => {
+ if (err.code === ICLOUD_NOT_MATERIALIZED) {
+ console.warn(`⚠️ Obsidian note evicted from local storage; skipping: ${fullPath}`);
+ return null;
+ }
+ throw err;
+ });
+}
+
/**
* Scan a vault for markdown files. Reads only frontmatter (not full content)
* for performance. Full content is loaded on individual note reads.
@@ -183,7 +205,8 @@ async function walkDir(rootPath, currentPath, results, folderFilter) {
const stats = await stat(fullPath);
// Read only first 2KB for frontmatter + inline tags (skip full content)
- const fd = await readFile(fullPath, { encoding: 'utf-8', flag: 'r' });
+ const fd = await readNoteContent(fullPath);
+ if (fd === null) continue;
const header = fd.length > 2048 ? fd.slice(0, 2048) : fd;
const { frontmatter, tags } = parseNoteMetadata(header);
@@ -211,7 +234,11 @@ export async function getNote(vaultId, notePath, { includeBacklinks = true } = {
}
if (!existsSync(fullPath)) return { error: 'NOTE_NOT_FOUND' };
- const content = await readFile(fullPath, 'utf-8');
+ const content = await readNoteContent(fullPath);
+ // Evicted, not missing — a distinct code so the UI can say "iCloud hasn't
+ // downloaded this note yet" instead of claiming it doesn't exist. The read was
+ // never issued, and a background `brctl download` is already in flight.
+ if (content === null) return { error: 'NOTE_EVICTED' };
const stats = await stat(fullPath);
const { frontmatter, tags, wikilinks, body } = parseNoteMetadata(content);
@@ -355,7 +382,7 @@ async function searchDir(rootPath, currentPath, query, countRe, results) {
for (const entry of entries) {
if (entry.name.startsWith('.') || SKIP_DIRS.has(entry.name)) continue;
if (entry.isFile() && extname(entry.name) === '.md') {
- contentReads.set(entry.name, readFile(join(currentPath, entry.name), 'utf-8'));
+ contentReads.set(entry.name, readNoteContent(join(currentPath, entry.name)));
}
}
@@ -367,6 +394,7 @@ async function searchDir(rootPath, currentPath, query, countRe, results) {
await searchDir(rootPath, fullPath, query, countRe, results);
} else if (entry.isFile() && extname(entry.name) === '.md') {
const content = await contentReads.get(entry.name);
+ if (content === null) continue; // evicted from iCloud — skip, don't block
const contentLower = content.toLowerCase();
const nameLower = basename(entry.name, '.md').toLowerCase();
const titleMatch = nameLower.includes(query);
@@ -449,7 +477,7 @@ async function collectNotes(rootPath, currentPath, noteMap, nodes) {
for (const entry of entries) {
if (entry.name.startsWith('.') || SKIP_DIRS.has(entry.name)) continue;
if (entry.isFile() && extname(entry.name) === '.md') {
- contentReads.set(entry.name, readFile(join(currentPath, entry.name), 'utf-8'));
+ contentReads.set(entry.name, readNoteContent(join(currentPath, entry.name)));
}
}
@@ -461,6 +489,7 @@ async function collectNotes(rootPath, currentPath, noteMap, nodes) {
await collectNotes(rootPath, fullPath, noteMap, nodes);
} else if (entry.isFile() && extname(entry.name) === '.md') {
const content = await contentReads.get(entry.name);
+ if (content === null) continue; // evicted from iCloud — skip, don't block
const relativePath = relative(rootPath, fullPath);
const noteName = basename(entry.name, '.md');
const { tags, wikilinks } = parseNoteMetadata(content);
@@ -577,7 +606,8 @@ async function findBacklinksInDir(rootPath, currentPath, targetLower, results) {
if (entry.isDirectory()) {
await findBacklinksInDir(rootPath, fullPath, targetLower, results);
} else if (entry.isFile() && extname(entry.name) === '.md') {
- const content = await readFile(fullPath, 'utf-8');
+ const content = await readNoteContent(fullPath);
+ if (content === null) continue; // evicted from iCloud — skip, don't block
WIKILINK_RE.lastIndex = 0;
let match;
while ((match = WIKILINK_RE.exec(content)) !== null) {
@@ -618,7 +648,8 @@ async function collectTags(rootPath, currentPath, tagCounts) {
if (entry.isDirectory()) {
await collectTags(rootPath, fullPath, tagCounts);
} else if (entry.isFile() && extname(entry.name) === '.md') {
- const content = await readFile(fullPath, 'utf-8');
+ const content = await readNoteContent(fullPath);
+ if (content === null) continue; // evicted from iCloud — skip, don't block
const { tags } = parseNoteMetadata(content);
for (const tag of tags) {
tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);