Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: collapse mortalLoomStore pinAgainstEviction into shared icloudFile helper (#3705)
Adam Eivy21024c30d342
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a9897d76b0..9df926fecc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,8 @@- **[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.+- Internal: [issue-3705] the MortalLoom store's boot/settings-change eviction pin no longer carries its own copy of the `brctl download` spawn/detach/exit-handler plumbing — it now delegates to the shared `icloudFile.requestMaterialization` helper the read paths already use. The helper gained an explicit dedupe policy (`retryAfterExit`): the read paths stay tracked in its capped in-flight set so a later read can retry, while the pin opts out and keeps its own single-sticky-path dedupe (re-pin only when the configured path changes) plus an `onFailure` hook that clears the sticky path so a failed or killed pin can retry. The once-per-process "brctl not found on PATH" warning also folded into the shared flag, so it fires at most once across the pin, read, and write paths rather than once per caller. No behavior change; ~40 lines of duplicated spawn plumbing removed.+## 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/server/lib/README.md b/server/lib/README.mdindex 89b163d0a7..503f7d1b7a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -148,7 +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) cloud files**. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a `~/Library/CloudStorage` File Provider mount); 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+encoding share a single read. `isUbiquityPath(path)` resolves the containing directory's real path (memoized) rather than substring-matching, so a **symlinked** route into iCloud — `~/Documents/...` under "Desktop & Documents Folders" sync — is still recognized. `isDatalessStats(stats)` is the raw predicate (`size > 0 && blocks === 0`) and is **not safe alone** (a sparse or `decmpfs`-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via `isEvictedStats(path, stats)`, which is what a caller holding a `Stats` should use, or `isSuspectedDataless(path)` which does the `stat` itself. `requestMaterialization(path, label)` is the fire-and-forget, per-path-deduped `brctl download` read paths kick to heal an evicted file — capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at `DOWNLOAD_DEADLINE_MS` so a wedged `brctl` can't hold every slot for the life of the process. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. |+| `icloudFile.js` | Guards against blocking reads of **evicted (dataless) cloud files**. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a `~/Library/CloudStorage` File Provider mount); 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+encoding share a single read. `isUbiquityPath(path)` resolves the containing directory's real path (memoized) rather than substring-matching, so a **symlinked** route into iCloud — `~/Documents/...` under "Desktop & Documents Folders" sync — is still recognized. `isDatalessStats(stats)` is the raw predicate (`size > 0 && blocks === 0`) and is **not safe alone** (a sparse or `decmpfs`-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via `isEvictedStats(path, stats)`, which is what a caller holding a `Stats` should use, or `isSuspectedDataless(path)` which does the `stat` itself. `requestMaterialization(path, {label, retryAfterExit, onFailure})` is the fire-and-forget `brctl download` every brctl caller shares — read paths kick it (default `retryAfterExit: true`) to heal an evicted file, per-path-deduped in a shared in-flight set capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at `DOWNLOAD_DEADLINE_MS` so a wedged `brctl` can't hold every slot for the life of the process; the boot/settings pin in `mortalLoomStore` passes `retryAfterExit: false` so it is NOT tracked in that shared set (it owns a single-sticky-path dedupe at its call site) plus an `onFailure` hook to clear that sticky path on a failed/killed download. `claimBrctlMissingWarning()` returns `true` on the first call only, so the "brctl not found on PATH" warning fires at most once per process across every brctl caller (the fire-and-forget path here and awaited write-path variants like `mortalLoomStore.materializeNow`). 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.jsindex 37510acc39..111034bd33 100644--- a/server/lib/icloudFile.js+++ b/server/lib/icloudFile.js@@ -158,8 +158,15 @@ export async function isSuspectedDataless(path) {// 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.-function markBrctlMissing() {+/**+ * Claim the one-shot "brctl is missing" warning. Returns true on the first call+ * only, false thereafter. Exported so every brctl caller in the process — the+ * fire-and-forget `requestMaterialization` read/pin path AND awaited write-path+ * variants like `mortalLoomStore.materializeNow` — shares ONE flag and the+ * "brctl not found on PATH" warning fires at most once per process across all of+ * them (rather than once per caller).+ */+export function claimBrctlMissingWarning() {if (brctlMissingWarned) return false;brctlMissingWarned = true;return true;@@ -192,16 +199,39 @@ export function _setDownloadDeadlineForTest(ms) { DOWNLOAD_DEADLINE_MS = ms; }* 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.+ * this and then refuse the read for *this* cycle. Returns `true` when a child+ * was spawned, `false` when the request was declined (non-darwin, non-iCloud+ * path, deduped, or capped).+ *+ * @param {string} path+ * @param {object} [options]+ * @param {string} [options.label='iCloud file'] - Label for log lines.+ * @param {boolean} [options.retryAfterExit=true] - Dedupe policy. The read paths+ * pass `true`: the request is tracked in the shared in-flight `Set` (deduped+ * while a download runs, cleared on exit) so a later read can retry, and it+ * counts against the concurrency cap. The boot/settings pin passes `false`: it+ * owns a single-sticky-path dedupe at its call site (re-pin only when the+ * configured path changes), so it is NOT tracked here — that keeps a churn of+ * configured-path changes from parking stale pin entries in the shared set and+ * starving the read-heal slots.+ * @param {() => void} [options.onFailure] - Called when the child errors, exits+ * non-zero, or is killed (never on a clean exit-0). Lets an untracked caller+ * (the pin) clear its own sticky dedupe so a failed pin can be retried.*/-export function requestMaterialization(path, label = 'iCloud file') {+export function requestMaterialization(path, options = {}) {+ const { label = 'iCloud file', retryAfterExit = true, onFailure } = options;if (process.platform !== 'darwin' || !path) return false;// `brctl` speaks iCloud only. A third-party File Provider file (Dropbox /// Google Drive / OneDrive under ~/Library/CloudStorage) is still screened and// refused above — we just can't heal it, so don't spawn a doomed child.if (!isHealablePath(path)) return false;- if (pendingDownloads.has(path)) return false;- if (pendingDownloads.size >= MAX_PENDING_DOWNLOADS) return false;+ // Only the tracked (read) path uses the shared in-flight dedupe + cap; the pin+ // deduplicates at its own call site, so it neither reserves a slot nor is+ // blocked by the cap (its single configured path can't flood).+ if (retryAfterExit) {+ if (pendingDownloads.has(path)) return false;+ if (pendingDownloads.size >= MAX_PENDING_DOWNLOADS) return false;+ }// 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@@ -220,10 +250,11 @@ export function requestMaterialization(path, label = 'iCloud file') {}// `spawn` is synchronous, so no other read can interleave between the size// check above and this reservation.- pendingDownloads.set(path, child);- // Release only the entry THIS child owns (see the map's comment above).+ if (retryAfterExit) pendingDownloads.set(path, child);+ // Release only the entry THIS child owns (see the map's comment above). A no-op+ // for an untracked (pin) request, which was never added to the set.const release = () => {- if (pendingDownloads.get(path) === child) pendingDownloads.delete(path);+ if (retryAfterExit && pendingDownloads.get(path) === child) pendingDownloads.delete(path);};// Kill the child if it outlives its deadline, so a wedged `brctl` frees its slot// instead of holding it forever. `unref` so the timer itself never keeps the@@ -231,8 +262,11 @@ export function requestMaterialization(path, label = 'iCloud file') {const deadline = setTimeout(() => {console.warn(`⚠️ brctl download exceeded ${DOWNLOAD_DEADLINE_MS}ms for ${label}; killing: ${path}`);// The child is detached (its own process group), so a bare kill would leave- // any grandchildren behind — signal the group.- try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); }+ // any grandchildren behind — signal the group. `child.kill?.` because this+ // runs in an unref'd timer *outside* any request lifecycle: an uncaught throw+ // here (e.g. the fallback firing against a child that has already been reaped+ // and lost its `kill`) would crash the process with no `next(err)` to catch it.+ try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill?.('SIGKILL'); }// A killed-but-unreaped child would strand the slot; drop it now so healing// can resume even if 'exit' never fires.release();@@ -244,8 +278,9 @@ export function requestMaterialization(path, label = 'iCloud file') {// dedupe entry for a different path.child.on('error', (err) => {settle();+ onFailure?.();if (err.code === 'ENOENT') {- if (markBrctlMissing()) {+ if (claimBrctlMissingWarning()) {console.warn(`⚠️ brctl not found on PATH; ${label} materialization disabled`);}return;@@ -256,7 +291,10 @@ export function requestMaterialization(path, label = 'iCloud file') {settle();if (code === 0) {console.log(`📥 ${label} materialized from iCloud: ${path}`);- } else if (code !== null) {+ return;+ }+ onFailure?.();+ if (code !== null) {console.warn(`⚠️ brctl download exited ${code} for ${label}: ${path}`);} else {console.warn(`⚠️ brctl download killed by ${signal} for ${label}: ${path}`);@@ -297,7 +335,7 @@ export async function readIfMaterialized(path, options = {}) {async function guardedRead(path, options) {const { encoding = 'utf-8', label = 'iCloud file' } = options;if (await isSuspectedDataless(path)) {- requestMaterialization(path, label);+ 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;diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsindex eb0eb30c83..6c3870762a 100644--- a/server/services/mortalLoomStore.js+++ b/server/services/mortalLoomStore.js@@ -13,10 +13,9 @@ import { join, dirname, basename } from 'path';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, isEvictedStats, readIfMaterialized, requestMaterialization } from '../lib/icloudFile.js';+import { ICLOUD_NOT_MATERIALIZED, claimBrctlMissingWarning, isEvictedStats, readIfMaterialized, requestMaterialization } from '../lib/icloudFile.js';import { isPlainObject } from '../lib/objects.js';import { getSettings, settingsEvents } from './settings.js';@@ -98,60 +97,34 @@ export function defaultStorePath() { return DEFAULT_ICLOUD_PATH; }// on-EAGAIN path handles that case. Best-effort, fire-and-forget; on// non-macOS we never spawn brctl, and on macOS when brctl is unexpectedly// missing (sandboxed env, removed binary) we warn ONCE and then fall-// through to the retry path silently — without the dedupe, every-// settings:updated would re-warn.+// through to the retry path silently.let lastPinnedPath = null;-let brctlMissingWarned = false;+// The boot/settings-change pin. The spawn + detach/unref + error/exit handler+// plumbing (and the shared once-per-process "brctl missing" warning) all live in+// the shared `requestMaterialization` helper now — this call site only owns the+// pin's distinct dedupe policy: a single sticky `lastPinnedPath` that persists+// after a *successful* pin (one configured path at a time; re-pin only when the+// path changes). `retryAfterExit: false` keeps the shared helper from tracking+// the pin in its in-flight read-heal set. `onFailure` clears the sticky path so a+// failed / signal-killed pin can be retried on the next settings:updated — and+// the captured `path` guard confines that clear to the pin's own path, so a stale+// child's late failure can't null the cache for a path that has since moved on.function pinAgainstEviction(path) {if (process.platform !== 'darwin') return;if (!path || lastPinnedPath === path) return;lastPinnedPath = path;-- // detached + unref so a long-running `brctl download` (large evicted file,- // slow network) can't keep the Node process alive on shutdown. Matches the- // repo's fire-and-forget spawn pattern in server/routes/apps/launch.js +- // server/routes/brain.js.- const child = spawn('brctl', ['download', path], { detached: true, stdio: 'ignore' });- child.unref();- // Capture `path` in each handler so a late-arriving error/exit from a stale- // child (one whose path has since been replaced by a newer pinAgainstEviction- // call) doesn't clear the dedupe cache for the *current* path. Without this- // capture, the stale exit would null out lastPinnedPath even though the new- // path's child is still in flight (or has already succeeded), defeating- // dedupe and causing repeated spawns on subsequent settings:updated events.- child.on('error', (err) => {- if (lastPinnedPath === path) lastPinnedPath = null;- if (err.code === 'ENOENT') {- // brctl isn't in PATH. On darwin this is extremely unusual; surface it- // once so operators in a sandbox aren't left wondering why pinning is- // a silent no-op, then dedupe so we don't spam on every settings change.- if (!brctlMissingWarned) {- brctlMissingWarned = true;- console.warn('⚠️ brctl not found on PATH; MortalLoom store pinning disabled (retry-on-EAGAIN path remains)');- }- return;- }- console.warn(`⚠️ brctl download failed for MortalLoom store: ${err.message}`);- });- child.on('exit', (code, signal) => {- if (code === 0) {- console.log(`📥 MortalLoom store pinned for download: ${path}`);- return;- }- // Non-zero exit OR signal-kill (code===null,signal set). Either way the- // pin didn't complete, so clear the dedupe cache to allow a retry on the- // next settings:updated event. Without this, a SIGTERM'd brctl would- // permanently mask its own retry. Guard with the captured `path` so a- // stale child can't clear cache for a path that has already moved on.- if (lastPinnedPath === path) lastPinnedPath = null;- if (code !== null) {- console.warn(`⚠️ brctl download exited ${code} for MortalLoom store: ${path}`);- } else {- console.warn(`⚠️ brctl download killed by ${signal} for MortalLoom store: ${path}`);- }+ const spawned = requestMaterialization(path, {+ label: 'MortalLoom store',+ retryAfterExit: false,+ onFailure: () => { if (lastPinnedPath === path) lastPinnedPath = null; },});+ // The helper declined to spawn (a non-iCloud configured path, or a synchronous+ // spawn failure — the non-darwin case is already handled above). Clear the+ // sticky path so a corrected/healable path on the next settings:updated isn't+ // wrongly deduped as "already pinned".+ if (!spawned && lastPinnedPath === path) lastPinnedPath = null;}// === On-demand (blocking) materialization for the write path ===@@ -195,10 +168,10 @@ async function materializeNow(path) {});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;+ // brctl missing — claim the shared once-per-process flag in icloudFile so the+ // "brctl not found" warning fires at most once across BOTH this write path and+ // the fire-and-forget pin/read paths in requestMaterialization.+ if (claimBrctlMissingWarning()) {console.warn('⚠️ brctl not found on PATH; MortalLoom on-demand materialize disabled (refuse-to-overwrite guard remains)');}} else if (result.timedOut) {@@ -225,7 +198,8 @@ export function _resetMortalLoomInitForTest() {listenerAttached = false;didInitialPin = false;lastPinnedPath = null;- brctlMissingWarned = false;+ // The once-per-process "brctl missing" flag now lives in icloudFile; tests that+ // need it cleared reset it via icloudFile._resetICloudFileStateForTest().}/**@@ -697,7 +671,7 @@ export async function getStatus() {const evicted = isEvictedStats(path, st);if (evicted) {console.warn(`⚠️ MortalLoom store evicted from local storage; status summary unavailable: ${path}`);- requestMaterialization(path, 'MortalLoom store');+ requestMaterialization(path, { label: 'MortalLoom store' });}const raw = st && !evicted ? await withTransientRetry(() => readIfMaterialized(path, { label: 'MortalLoom store' })).catch((err) => {if (err.code === 'ENOENT') { readEnoent = true; return null; }diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.jsindex 6101faa46f..a231c8ef87 100644--- a/server/services/mortalLoomStore.test.js+++ b/server/services/mortalLoomStore.test.js@@ -665,6 +665,15 @@ describe('readStore — EAGAIN retry', () => {});describe('initMortalLoomStore — brctl pinning', () => {+ // The pin now delegates to icloudFile.requestMaterialization, which only spawns+ // `brctl download` for genuinely healable iCloud paths (a path inside+ // `/Library/Mobile Documents/`). Use REAL ubiquity paths here — the ordinary+ // `/icloud/...` fixture the rest of this suite uses is deliberately NOT a+ // ubiquity path, so it would be (correctly) declined and never spawn. The+ // literal `/Library/Mobile Documents/` substring makes isHealablePath resolve+ // without a `realpath` (fs is mocked here), so these paths spawn as expected.+ const ubiq = (name) => `/Users/example/Library/Mobile Documents/iCloud~net~example~App/Documents/${name}`;+const makeFakeChild = () => {const handlers = {};const child = {@@ -680,9 +689,14 @@ describe('initMortalLoomStore — brctl pinning', () => {// afterEach so an assertion failure can't leak the mutated platform into// unrelated test files (mirrors the updateExecutor.test.js pattern).let originalPlatformDescriptor;- beforeEach(() => {+ beforeEach(async () => {settingsEvents.removeAllListeners('settings:updated');store._resetMortalLoomInitForTest();+ // The once-per-process "brctl missing" warning flag now lives in icloudFile+ // (folded from the store's old local flag). Reset it here so the missing-brctl+ // dedupe test starts from a clean slate regardless of test order.+ const icloud = await import('../lib/icloudFile.js');+ icloud._resetICloudFileStateForTest();originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');});afterEach(() => {@@ -697,7 +711,7 @@ describe('initMortalLoomStore — brctl pinning', () => {const child = makeFakeChild();spawnMock.mockReturnValue(child);- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();@@ -706,7 +720,7 @@ describe('initMortalLoomStore — brctl pinning', () => {// pattern. Without both, a slow brctl download blocks process exit.expect(spawnMock).toHaveBeenCalledWith('brctl',- ['download', '/icloud/MortalLoom.json'],+ ['download', ubiq('MortalLoom.json')],expect.objectContaining({ detached: true, stdio: 'ignore' }));expect(child.unref).toHaveBeenCalledTimes(1);@@ -716,17 +730,17 @@ describe('initMortalLoomStore — brctl pinning', () => {Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });spawnMock.mockReturnValue(makeFakeChild());- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();const initialCalls = spawnMock.mock.calls.length;// Same path: deduped, no new spawn.- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } });expect(spawnMock.mock.calls.length).toBe(initialCalls);// New path: re-pins.- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/other/MortalLoom.json' } });- expect(spawnMock).toHaveBeenLastCalledWith('brctl', ['download', '/icloud/other/MortalLoom.json'], expect.any(Object));+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('other/MortalLoom.json') } });+ expect(spawnMock).toHaveBeenLastCalledWith('brctl', ['download', ubiq('other/MortalLoom.json')], expect.any(Object));});it('no-ops on non-darwin platforms (init pin AND settings-change re-pin both guarded)', async () => {@@ -737,11 +751,11 @@ describe('initMortalLoomStore — brctl pinning', () => {// thing under test on both the immediate-pin and the event-driven path.Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();expect(spawnMock).not.toHaveBeenCalled();- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } });expect(spawnMock).not.toHaveBeenCalled();});@@ -762,8 +776,8 @@ describe('initMortalLoomStore — brctl pinning', () => {// Listener was attached before the failing await, so a later event still// fires pinAgainstEviction.- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });- expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.any(Object));+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } });+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', ubiq('MortalLoom.json')], expect.any(Object));});it('reads settings exactly once during init (no half-fail window)', async () => {@@ -779,12 +793,12 @@ describe('initMortalLoomStore — brctl pinning', () => {// Other tests in this file accumulate calls on the shared getSettings// mock — clear before asserting count to isolate this test's call pattern.getSettings.mockClear();- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();expect(getSettings).toHaveBeenCalledTimes(1);- expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.any(Object));+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', ubiq('MortalLoom.json')], expect.any(Object));});it('retries the initial pin on a subsequent call when the first attempt threw', async () => {@@ -802,15 +816,15 @@ describe('initMortalLoomStore — brctl pinning', () => {expect(spawnMock).not.toHaveBeenCalled();// Second call: getSettings recovers, initial pin proceeds.- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();expect(spawnMock).toHaveBeenCalledTimes(1);- expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.any(Object));+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', ubiq('MortalLoom.json')], expect.any(Object));// Listener was attached on the first call, not the second — emitting once// must fire pinAgainstEviction once, not twice.spawnMock.mockClear();- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/other/MortalLoom.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('other/MortalLoom.json') } });expect(spawnMock).toHaveBeenCalledTimes(1);});@@ -822,18 +836,18 @@ describe('initMortalLoomStore — brctl pinning', () => {Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });spawnMock.mockReturnValue(makeFakeChild());- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();expect(spawnMock).toHaveBeenCalledTimes(1);// User disables sync — no spawn, but the dedup cache must clear.- settingsEvents.emit('settings:updated', { mortalloom: { enabled: false, path: '/icloud/MortalLoom.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: false, path: ubiq('MortalLoom.json') } });expect(spawnMock).toHaveBeenCalledTimes(1);// Re-enable with the SAME path — should re-spawn brctl, not be deduped.- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } });expect(spawnMock).toHaveBeenCalledTimes(2);- expect(spawnMock).toHaveBeenLastCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.any(Object));+ expect(spawnMock).toHaveBeenLastCalledWith('brctl', ['download', ubiq('MortalLoom.json')], expect.any(Object));});it('clears lastPinnedPath when brctl is signal-killed so a later event can retry', async () => {@@ -841,7 +855,7 @@ describe('initMortalLoomStore — brctl pinning', () => {const child = makeFakeChild();spawnMock.mockReturnValue(child);- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();expect(spawnMock).toHaveBeenCalledTimes(1);@@ -850,7 +864,7 @@ describe('initMortalLoomStore — brctl pinning', () => {// would stay poisoned and a subsequent settings:updated for the same path// would no-op forever.child._emit('exit', null, 'SIGTERM');- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } });expect(spawnMock).toHaveBeenCalledTimes(2);});@@ -865,7 +879,7 @@ describe('initMortalLoomStore — brctl pinning', () => {const child1 = makeFakeChild();const child2 = makeFakeChild();spawnMock.mockReturnValueOnce(child1).mockReturnValueOnce(child2);- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();// First brctl process fires error with ENOENT.@@ -876,7 +890,7 @@ describe('initMortalLoomStore — brctl pinning', () => {);// Re-emit settings:updated with a DIFFERENT path so dedupe doesn't gate.- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/other.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('other.json') } });child2._emit('error', Object.assign(new Error('not found'), { code: 'ENOENT' }));// No second warning — the missing-binary dedupe held.expect(console.warn).toHaveBeenCalledTimes(1);@@ -895,20 +909,20 @@ describe('initMortalLoomStore — brctl pinning', () => {const child1 = makeFakeChild();const child2 = makeFakeChild();spawnMock.mockReturnValueOnce(child1).mockReturnValueOnce(child2);- settings = { mortalloom: { enabled: true, path: '/icloud/A.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('A.json') } };await store.initMortalLoomStore();expect(spawnMock).toHaveBeenCalledTimes(1);// Newer pin for path B kicks off (e.g. user changed path before A's// child finished). Cache now points to B, child2 is in flight.- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/B.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('B.json') } });expect(spawnMock).toHaveBeenCalledTimes(2);// Stale child1 finally errors. Must NOT clear the B cache.child1._emit('error', Object.assign(new Error('boom'), { code: 'EAGAIN' }));// Re-emit settings:updated for B — dedupe should still hold (no spawn).- settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/B.json' } });+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ubiq('B.json') } });expect(spawnMock).toHaveBeenCalledTimes(2);});@@ -920,7 +934,7 @@ describe('initMortalLoomStore — brctl pinning', () => {Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });spawnMock.mockReturnValue(makeFakeChild());- settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ settings = { mortalloom: { enabled: true, path: ubiq('MortalLoom.json') } };await store.initMortalLoomStore();spawnMock.mockClear();