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-3706]): guard Obsidian updateNote against a blocking write to an evicted iCloud note

[._.]/ Adam Eivy7d6dc90ad31e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 394fc0a350..f8cc10fb9e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,10 @@
- **[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.
+- **[issue-3706] Saving a note that iCloud has offloaded no longer risks freezing the UI.** [issue-3704] stopped offloaded files from stalling PortOS when they were *read*, but saving over one was still unguarded — and measuring it showed that overwriting an offloaded note stalls exactly like reading it, even though the save replaces every byte of the file. That matters more than a manual save: your Brain daily-log mirror and YouTube transcript ingest write notes on their own schedule, so a stuck iCloud could have frozen every page with nobody at the keyboard. PortOS now checks before saving, asks iCloud for the note and waits briefly, and if it still hasn't arrived reports "temporarily unavailable" for that one note — leaving its existing contents untouched — instead of hanging. Background mirrors skip that note quietly and pick it up on their next pass.
+
+- Internal: [issue-3706] the awaited `brctl download` used before an overwrite moved out of `mortalLoomStore` into the shared `icloudFile.materializeAndWait`, now that Obsidian's `updateNote` needs the identical bounded materialize — the second caller is what earned the extraction. It also no longer throws when `spawn` fails synchronously (EMFILE under load), which would otherwise surface from a save as a raw spawn error instead of the handled refusal. The module docblock gained a measured syscall table — `stat`/`open`/`rename` never materialize a dataless file, while `read`, `write` (including after `O_TRUNC` — truncating does **not** skip the download), `link`, and `clonefile` all do — so the next reader doesn't re-derive it from first principles and reach the intuitive, wrong conclusion.
+
- 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 map 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. ~40 lines of duplicated spawn plumbing removed. Two small, deliberate behavior changes come with the consolidation: the pin now inherits the shared 120s download deadline (a wedged boot pin is SIGKILL'd and left to the next `settings:updated` to retry, instead of lingering unref'd forever), and it now only spawns `brctl` for genuine iCloud (`/Library/Mobile Documents/`) paths rather than any macOS path — the pin exists solely for the iCloud store, so a non-iCloud configured path is no longer handed a doomed `brctl download`.
## Added
diff --git a/server/lib/README.md b/server/lib/README.md
index 736c70704a..46ba38e183 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, 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 map 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 map (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`. |
+| `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 **data access** 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 map 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 map (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 the awaited `materializeAndWait`). `materializeAndWait(path, {label, timeoutMs})` is the **awaited, bounded** counterpart used by WRITE paths (`mortalLoomStore` before overwriting its store, `obsidian.updateNote` before overwriting a note): a write must not silently skip, so it materializes and waits rather than firing and forgetting, bounded by `MATERIALIZE_TIMEOUT_MS` (20s — much tighter than the background `DOWNLOAD_DEADLINE_MS` because a caller is blocked on it) and run in a child process, which is what makes the wait cancellable when the kernel write it replaces would not be. It resolves `true` only on brctl exit-0, which means the download was **accepted, not completed** — always re-screen before trusting the file. Measured (#3706), and recorded in the module docblock's syscall table: `stat`/`open`/`rename` never materialize, while `read`, `write` (including after `O_TRUNC` — truncating does NOT skip the download), `link`, and `clonefile` all do; `unlink` is untested, so don't assume it's free. 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
index 6a3f593032..25d197f5c0 100644
--- a/server/lib/icloudFile.js
+++ b/server/lib/icloudFile.js
@@ -20,6 +20,40 @@
* 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.
*
+ * ## Which syscalls actually materialize (measured, #3706)
+ *
+ * The trigger is the first **data access**, not the `open(2)`. Measured on
+ * macOS 26 (Darwin 25.5, APFS) against freshly-evicted iCloud files — a fresh
+ * subject per case, since the first materializing call heals the file:
+ *
+ * | syscall | materializes? | cost on a HEALTHY iCloud |
+ * |----------------------------------|---------------|--------------------------|
+ * | `stat` | no | instant |
+ * | `open` — `'r'`, `'a'`, `'r+'` | no | 0 ms |
+ * | `rename` | no | 0–1 ms |
+ * | `read` | **yes** | ~900 ms |
+ * | `write` after `O_TRUNC` (`'w'`) | **yes** | ~820 ms |
+ * | `write` in append mode (`'a'`) | **yes** | ~690 ms |
+ * | `link` (hard link) | **yes** | — |
+ * | `clonefile` (`cp -c`) | **yes** | — |
+ *
+ * Two consequences that are easy to get wrong:
+ *
+ * 1. **`O_TRUNC` does NOT short-circuit materialization.** Truncating to zero
+ * discards every byte the download would fetch, so "there is nothing to
+ * materialize" is an appealing inference — and it is wrong. The same
+ * `writeFile(path, content, 'utf-8')` cost 822 ms dataless and **1 ms** once
+ * materialized, on the same path with only the dataless bit changed (a
+ * non-iCloud local file: 0 ms). That ~800 ms is the download, not iCloud
+ * write coordination. So a *write* path needs the same screen as a read path.
+ * 2. **Screening is free.** `stat` and `open` never materialize, so a guard
+ * costs nothing on the healthy path — including `existsSync` precondition
+ * checks, which can stay exactly where they are.
+ *
+ * `unlink` is deliberately absent above: it is untested. Do not assume it is
+ * free by analogy with `rename` — `link` is also pure metadata and it *does*
+ * materialize.
+ *
* ## The screen
*
* `stat()` is safe — it does NOT trigger materialization and returns instantly
@@ -49,6 +83,7 @@ import { readFile, stat } from 'fs/promises';
import { realpathSync } from 'fs';
import { dirname } from 'path';
import { spawn } from 'child_process';
+import { bufferedSpawn } from './bufferedSpawn.js';
import { createSingleFlight } from './singleFlight.js';
/** `err.code` on the rejection `readIfMaterialized` throws for an evicted file. */
@@ -195,6 +230,13 @@ const MAX_PENDING_DOWNLOADS = 4;
export let DOWNLOAD_DEADLINE_MS = 120_000;
export function _setDownloadDeadlineForTest(ms) { DOWNLOAD_DEADLINE_MS = ms; }
+// Default deadline for the AWAITED write-path materialize (`materializeAndWait`).
+// Much tighter than DOWNLOAD_DEADLINE_MS above because a caller is blocked on it:
+// a background heal can afford two minutes, a user's save cannot. Exposed (not
+// const) so tests don't wait on it.
+export let MATERIALIZE_TIMEOUT_MS = 20_000;
+export function _setMaterializeTimeoutForTest(ms) { MATERIALIZE_TIMEOUT_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
@@ -333,6 +375,67 @@ export function requestMaterialization(path, options = {}) {
return true;
}
+/**
+ * `brctl download <path>`, **awaited** and bounded by a timeout.
+ *
+ * The write-path counterpart to `requestMaterialization`. A read path can fire
+ * and forget because it refuses the read for this cycle and a later read retries;
+ * a *write* path has no such luxury — it must not silently skip the write, and it
+ * must not issue a blocking one either (measured: a write to a dataless file
+ * materializes, see the syscall table above). So it materializes first, waits for
+ * the result, and lets the caller fail loudly if that didn't work.
+ *
+ * Runs `brctl` in a child process, which is what makes the wait cancellable: the
+ * kernel write this replaces cannot be interrupted, but a wedged `brctl` is just
+ * a child that misses its deadline and gets killed. That is the whole point of
+ * routing through `brctl` rather than letting the write block.
+ *
+ * Resolves `true` only when `brctl` exited 0. **That means the download was
+ * ACCEPTED, not that the bytes are local** — `brctl` can return 0 before
+ * materialization completes. Always re-screen (or use a reader that re-screens)
+ * before trusting the file; never drop a subsequent guard on the strength of a
+ * `true` here.
+ *
+ * Never throws: every failure mode (missing `brctl`, timeout, non-zero exit)
+ * warns and resolves `false`.
+ *
+ * @param {string} path
+ * @param {object} [options]
+ * @param {string} [options.label='iCloud file'] - Label for log lines.
+ * @param {number} [options.timeoutMs=MATERIALIZE_TIMEOUT_MS] - Deadline for the child.
+ */
+export async function materializeAndWait(path, options = {}) {
+ const { label = 'iCloud file', timeoutMs = MATERIALIZE_TIMEOUT_MS } = options;
+ if (process.platform !== 'darwin' || !path) return false;
+ // try/catch at a child-process boundary (permitted by the repo's no-try/catch
+ // rule, and mirroring `requestMaterialization` above): `spawn` can throw
+ // SYNCHRONOUSLY on resource exhaustion (EMFILE), and `bufferedSpawn` lets that
+ // propagate rather than folding it into a result. A failed *heal* must never
+ // replace the caller's clean "still evicted, write refused" verdict with a
+ // spawn error — the write is correctly refused either way.
+ let result;
+ try {
+ result = await bufferedSpawn('brctl', ['download', path], { timeoutMs, shell: false });
+ } catch (err) {
+ result = { success: false, error: err };
+ }
+ if (result.success) return true;
+ if (result.error?.code === 'ENOENT') {
+ // Share the once-per-process flag with the fire-and-forget paths so the
+ // "brctl missing" warning fires at most once across all of them.
+ if (claimBrctlMissingWarning()) {
+ 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;
+}
+
// N concurrent callers for the same path share ONE underlying read, so they
// occupy at most one threadpool slot between them. The shared coalescer clears
// each slot as soon as the read settles, so a later call re-reads — this
diff --git a/server/lib/icloudFile.test.js b/server/lib/icloudFile.test.js
index 10934413c8..b2f1bcfeaf 100644
--- a/server/lib/icloudFile.test.js
+++ b/server/lib/icloudFile.test.js
@@ -7,12 +7,20 @@ const statMock = vi.fn();
const readFileMock = vi.fn();
const spawnMock = vi.fn();
-vi.mock('fs/promises', () => ({
+// Partial mocks (spread the original) rather than bare replacements: icloudFile
+// pulls in `bufferedSpawn` -> `spawnCwd` -> `fileUtils` for the awaited
+// `materializeAndWait`, and those need the real `execFile`/`fs/promises` exports.
+// A bare replacement makes the whole suite fail to import with "No X export is
+// defined on the mock", which looks like 39 broken assertions rather than one
+// missing export.
+vi.mock('fs/promises', async (importOriginal) => ({
+ ...await importOriginal(),
stat: (...args) => statMock(...args),
readFile: (...args) => readFileMock(...args),
}));
-vi.mock('child_process', () => ({
+vi.mock('child_process', async (importOriginal) => ({
+ ...await importOriginal(),
spawn: (...args) => spawnMock(...args),
}));
@@ -514,3 +522,77 @@ describe('background download slot ownership', () => {
}
});
});
+
+/**
+ * The awaited, bounded write-path materialize (#3706).
+ *
+ * Distinct from `requestMaterialization` above in the one way that matters: a
+ * write path cannot fire-and-forget, because skipping a write silently loses the
+ * user's edit. So this one waits for brctl and reports whether it worked — and
+ * bounds the wait, since brctl is exactly what hangs when iCloud is wedged.
+ */
+describe('materializeAndWait', () => {
+ // Shaped for the shared bufferedSpawn helper, which reads child.stdout/stderr
+ // and resolves on `close`. (The suite's global beforeEach already pins
+ // platform=darwin and silences console; don't re-stub either here.)
+ const makeChild = (exitCode) => {
+ const noopStream = { on: vi.fn() };
+ const child = {
+ stdout: noopStream,
+ stderr: noopStream,
+ pid: 4242,
+ on: vi.fn(function (evt, cb) {
+ if (evt === 'close') setTimeout(() => cb(exitCode, null), 0);
+ return child;
+ }),
+ kill: vi.fn(),
+ unref: vi.fn(),
+ };
+ return child;
+ };
+
+ it('awaits brctl and resolves true on a clean exit', async () => {
+ spawnMock.mockReturnValue(makeChild(0));
+ await expect(icloud.materializeAndWait(ICLOUD_PATH)).resolves.toBe(true);
+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', ICLOUD_PATH], expect.objectContaining({ shell: false }));
+ });
+
+ it('resolves false on a non-zero exit so the caller refuses the write', async () => {
+ spawnMock.mockReturnValue(makeChild(1));
+ await expect(icloud.materializeAndWait(ICLOUD_PATH)).resolves.toBe(false);
+ });
+
+ it('is inert off darwin — no child spawned', async () => {
+ platformSpy.mockReturnValue('linux');
+ await expect(icloud.materializeAndWait(ICLOUD_PATH)).resolves.toBe(false);
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('resolves false for an empty path without spawning', async () => {
+ await expect(icloud.materializeAndWait('')).resolves.toBe(false);
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('resolves false instead of THROWING when spawn fails synchronously', async () => {
+ // bufferedSpawn lets a synchronous spawn throw (EMFILE under load) propagate.
+ // Unguarded, that would surface from updateNote as a raw spawn error instead
+ // of the clean NOTE_EVICTED refusal — turning a handled degradation into a 500.
+ spawnMock.mockImplementation(() => { throw Object.assign(new Error('too many files'), { code: 'EMFILE' }); });
+ await expect(icloud.materializeAndWait(ICLOUD_PATH)).resolves.toBe(false);
+ });
+
+ it('shares the once-per-process brctl-missing warning with the read paths', async () => {
+ // Claiming it first (as a read path would) must silence the write path's copy,
+ // so an operator sees ONE "brctl not found" line per process, not one per caller.
+ expect(icloud.claimBrctlMissingWarning()).toBe(true);
+ spawnMock.mockImplementation(() => { throw Object.assign(new Error('nope'), { code: 'ENOENT' }); });
+ await expect(icloud.materializeAndWait(ICLOUD_PATH)).resolves.toBe(false);
+ expect(warnSpy.mock.calls.flat().join(' ')).not.toMatch(/brctl not found/);
+ });
+
+ it('does warn when the flag has NOT already been claimed', async () => {
+ spawnMock.mockImplementation(() => { throw Object.assign(new Error('nope'), { code: 'ENOENT' }); });
+ await expect(icloud.materializeAndWait(ICLOUD_PATH)).resolves.toBe(false);
+ expect(warnSpy.mock.calls.flat().join(' ')).toMatch(/brctl not found/);
+ });
+});
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index 32042a9c9f..2b85a06fad 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -14,8 +14,7 @@ import { stat } from 'fs/promises';
import { existsSync } from 'fs';
import { randomUUID } from 'crypto';
import { atomicWrite, safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';
-import { bufferedSpawn } from '../lib/bufferedSpawn.js';
-import { ICLOUD_NOT_MATERIALIZED, claimBrctlMissingWarning, isEvictedStats, readIfMaterialized, requestMaterialization } from '../lib/icloudFile.js';
+import { ICLOUD_NOT_MATERIALIZED, isEvictedStats, materializeAndWait, readIfMaterialized, requestMaterialization } from '../lib/icloudFile.js';
import { isPlainObject } from '../lib/objects.js';
import { getSettings, settingsEvents } from './settings.js';
@@ -182,33 +181,22 @@ function icloudPlaceholderPath(path) {
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.
+// Unlike pinAgainstEviction, this awaits brctl to completion (timeout + kill-tree
+// handled inside the shared helper). 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.
+//
+// The mechanics live in `icloudFile.materializeAndWait` — Obsidian's `updateNote`
+// needs the identical awaited-and-bounded materialize (#3706), so the second
+// caller is what earned the extraction. The local `MATERIALIZE_TIMEOUT_MS` is
+// passed explicitly rather than relying on the lib's default so this service
+// keeps its own test hook.
async function materializeNow(path) {
- if (process.platform !== 'darwin' || !path) return false;
- const result = await bufferedSpawn('brctl', ['download', path], {
+ return materializeAndWait(path, {
+ label: 'MortalLoom store',
timeoutMs: MATERIALIZE_TIMEOUT_MS,
- shell: false,
});
- if (result.success) return true;
- if (result.error?.code === 'ENOENT') {
- // 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) {
- 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
diff --git a/server/services/obsidian.js b/server/services/obsidian.js
index 326b41347d..6772faa617 100644
--- a/server/services/obsidian.js
+++ b/server/services/obsidian.js
@@ -11,7 +11,7 @@ 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';
+import { ICLOUD_NOT_MATERIALIZED, isSuspectedDataless, materializeAndWait, readIfMaterialized } from '../lib/icloudFile.js';
const VAULTS_FILE = join(PATHS.brain, 'obsidian-vaults.json');
@@ -279,6 +279,31 @@ export async function updateNote(vaultId, notePath, content) {
if (!fullPath) return { error: 'INVALID_PATH' };
if (!existsSync(fullPath)) return { error: 'NOTE_NOT_FOUND' };
+ // Overwriting an EVICTED note would block exactly like reading one — measured,
+ // not assumed: `writeFile`'s O_TRUNC does NOT skip materialization (822ms
+ // dataless vs 1ms materialized for the same call; see the syscall table in
+ // server/lib/icloudFile.js). Discarding every byte first is intuitively enough
+ // to make the download pointless, and the kernel disagrees.
+ //
+ // This matters beyond "a user clicked save": updateNote is reached from
+ // BACKGROUND mirrors via upsertNote — the Brain daily-log mirror and YouTube
+ // ingest — so a wedged iCloud could strand libuv threadpool slots with no user
+ // in the loop, which is the whole-UI outage #3704 fixed on the read side.
+ //
+ // A write must not silently skip, so unlike the read paths this materializes
+ // and WAITS (bounded, in a child process — cancellable, which the kernel write
+ // is not) rather than fire-and-forget. brctl exit 0 only means the download was
+ // accepted, so re-screen before trusting it and refuse if it's still dataless.
+ if (await isSuspectedDataless(fullPath)) {
+ await materializeAndWait(fullPath, { label: 'Obsidian note' });
+ if (await isSuspectedDataless(fullPath)) {
+ return {
+ error: 'NOTE_EVICTED',
+ message: 'This note is stored in iCloud and has not been downloaded to this Mac yet. A download was requested — try again shortly.'
+ };
+ }
+ }
+
await writeFile(fullPath, content, 'utf-8');
console.log(`📓 Updated note: ${notePath} in vault ${vault.name}`);
return await getNote(vaultId, notePath, { includeBacklinks: false });
@@ -299,6 +324,11 @@ export async function createNote(vaultId, notePath, content = '') {
return { error: 'NOTE_EXISTS', message: 'A note with this name already exists' };
}
+ // No eviction guard here, deliberately (#3706): the `existsSync` above means
+ // this only ever writes a file that does NOT exist, and a file that does not
+ // exist cannot be dataless — there is nothing offloaded to materialize. The
+ // overwrite case is `updateNote`, which is guarded. Don't add a screen here
+ // "for symmetry"; it would cost a stat per created note and can never fire.
await writeFile(fullPath, content, 'utf-8');
console.log(`📓 Created note: ${notePath} in vault ${vault.name}`);
return await getNote(vaultId, notePath, { includeBacklinks: false });
diff --git a/server/services/obsidianEvicted.test.js b/server/services/obsidianEvicted.test.js
index 36e0873fa7..aa8268bdf9 100644
--- a/server/services/obsidianEvicted.test.js
+++ b/server/services/obsidianEvicted.test.js
@@ -14,7 +14,7 @@
*/
import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
-import { mkdirSync, rmSync, writeFileSync } from 'fs';
+import { mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -28,6 +28,8 @@ vi.mock('../lib/fileUtils.js', async () => {
// Only `evicted.md` is treated as offloaded; every other path reads for real, so
// the assertions below distinguish "skipped that one note" from "read nothing".
+// `isSuspectedDataless` defaults to false so the reader tests below are unaffected
+// by the write-path guard; the write tests drive it per-case.
vi.mock('../lib/icloudFile.js', () => ({
ICLOUD_NOT_MATERIALIZED: 'ICLOUD_NOT_MATERIALIZED',
readIfMaterialized: vi.fn(async (path) => {
@@ -36,9 +38,11 @@ vi.mock('../lib/icloudFile.js', () => ({
}
return readFile(path, 'utf-8');
}),
+ isSuspectedDataless: vi.fn(async () => false),
+ materializeAndWait: vi.fn(async () => true),
}));
-const { addVault, scanVault, searchNotes, getVaultTags, getVaultGraph, getNote } =
+const { addVault, scanVault, searchNotes, getVaultTags, getVaultGraph, getNote, updateNote, createNote, upsertNote } =
await import('./obsidian.js');
const VAULT_DIR = join(tempRoot, 'vault');
@@ -110,3 +114,113 @@ describe('obsidian readers with an evicted note', () => {
await expect(getNote(vaultId, 'readable.md')).rejects.toThrow('boom');
});
});
+
+/**
+ * The WRITE side — #3706.
+ *
+ * Overwriting an evicted note blocks exactly like reading one: `writeFile`'s
+ * O_TRUNC does NOT skip materialization (measured — 822ms dataless vs 1ms
+ * materialized for the identical call). These pin that `updateNote` never issues
+ * that write, which is the whole defence: a blocked write cannot be cancelled,
+ * so the only safe move is not to make it.
+ *
+ * Assertions read the file back off disk rather than spying on `writeFile`, so
+ * they pin the OBSERVABLE outcome ("the note's bytes are untouched") instead of
+ * the current implementation's choice of fs call.
+ */
+describe('obsidian updateNote against an evicted note', () => {
+ const NOTE = 'readable.md';
+ const ORIGINAL = '---\ntags: [biology]\n---\nmitochondria here\n[[evicted]]\n';
+
+ beforeEach(async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockReset().mockResolvedValue(false);
+ icloud.materializeAndWait.mockReset().mockResolvedValue(true);
+ });
+
+ it('refuses the write and leaves the note byte-for-byte intact', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ // Still dataless on the re-screen after materializing => refuse.
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+
+ const result = await updateNote(vaultId, NOTE, 'REPLACEMENT');
+
+ expect(result.error).toBe('NOTE_EVICTED');
+ expect(result.message).toMatch(/iCloud/i);
+ // The load-bearing assertion: the blocking write was never issued.
+ expect(readFileSync(join(VAULT_DIR, NOTE), 'utf-8')).toBe(ORIGINAL);
+ });
+
+ it('materializes and WAITS rather than firing and forgetting', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+
+ await updateNote(vaultId, NOTE, 'REPLACEMENT');
+
+ // A write must not silently skip, so unlike the read paths this one has to
+ // await the download before deciding — hence materializeAndWait, never
+ // requestMaterialization.
+ expect(icloud.materializeAndWait).toHaveBeenCalledTimes(1);
+ // realpath'd: resolveVaultPath resolves the vault root, and the temp dir is
+ // reached through /var -> /private/var on macOS.
+ expect(icloud.materializeAndWait).toHaveBeenCalledWith(
+ join(realpathSync(VAULT_DIR), NOTE),
+ expect.objectContaining({ label: 'Obsidian note' })
+ );
+ });
+
+ it('writes normally once materialization actually lands', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ // Dataless on the first screen, materialized on the re-screen.
+ icloud.isSuspectedDataless.mockResolvedValueOnce(true).mockResolvedValue(false);
+
+ const result = await updateNote(vaultId, NOTE, 'REPLACEMENT');
+
+ expect(result.error).toBeUndefined();
+ expect(readFileSync(join(VAULT_DIR, NOTE), 'utf-8')).toBe('REPLACEMENT');
+ });
+
+ it('re-screens instead of trusting brctl exit-0', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+ // brctl exit-0 means the download was ACCEPTED, not that the bytes are local.
+ icloud.materializeAndWait.mockResolvedValue(true);
+
+ const result = await updateNote(vaultId, NOTE, 'REPLACEMENT');
+
+ // Trusting that `true` would issue the very write this guard exists to prevent.
+ expect(result.error).toBe('NOTE_EVICTED');
+ expect(icloud.isSuspectedDataless).toHaveBeenCalledTimes(2);
+ });
+
+ it('costs nothing on the healthy path — no materialize for a normal note', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+
+ const result = await updateNote(vaultId, NOTE, 'REPLACEMENT');
+
+ expect(result.error).toBeUndefined();
+ expect(icloud.materializeAndWait).not.toHaveBeenCalled();
+ expect(readFileSync(join(VAULT_DIR, NOTE), 'utf-8')).toBe('REPLACEMENT');
+ });
+
+ it('createNote does not screen — a file that does not exist cannot be dataless', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+
+ const result = await createNote(vaultId, 'brand-new.md', 'fresh');
+
+ expect(result.error).toBeUndefined();
+ // Pins the deliberate no-guard decision so a later "add it for symmetry"
+ // change has to argue with a test rather than slip through.
+ expect(icloud.isSuspectedDataless).not.toHaveBeenCalled();
+ });
+
+ it('upsertNote degrades to a skipped mirror, never a hang or a throw', async () => {
+ const icloud = await import('../lib/icloudFile.js');
+ icloud.isSuspectedDataless.mockResolvedValue(true);
+
+ // upsertNote is how the BACKGROUND mirrors (Brain daily log, YouTube ingest)
+ // reach updateNote — with no user in the loop, so it must fail quietly.
+ await expect(upsertNote(vaultId, NOTE, 'REPLACEMENT')).resolves.toBeNull();
+ expect(readFileSync(join(VAULT_DIR, NOTE), 'utf-8')).toBe(ORIGINAL);
+ });
+});