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]): address claude review — symlinked vaults, wedged brctl, silent skips

Adam Eivy5e13d468e763
diff --git a/client/src/components/settings/MortalLoomTab.jsx b/client/src/components/settings/MortalLoomTab.jsx
index c396549d1c..1ea8d4fc1a 100644
--- a/client/src/components/settings/MortalLoomTab.jsx
+++ b/client/src/components/settings/MortalLoomTab.jsx
@@ -57,6 +57,15 @@ export function MortalLoomTab() {
}
};
+// The server reports a machine-readable `reason`; these are the ones worth
+// rewriting for a human. An evicted (iCloud-offloaded) store is deliberately
+// distinct from a missing one — telling the user the file is "not found" would
+// invite them to repoint the path or re-seed on top of real data.
+const IMPORT_FAILURE_MESSAGES = {
+ 'mortalloom-file-not-found': 'MortalLoom.json was not found at the configured path.',
+ 'mortalloom-file-unreadable': 'MortalLoom.json is in iCloud but has not been downloaded to this Mac yet. A download was requested — try again shortly.',
+};
+
const handleImport = async () => {
if (!status?.exists) {
toast.error('MortalLoom.json not found at configured path');
@@ -66,7 +75,7 @@ export function MortalLoomTab() {
const res = await importMortalLoom({ silent: true }).catch(() => null);
setImporting(false);
if (!res?.ok) {
- toast.error('Import failed: ' + (res?.reason || 'unknown'));
+ toast.error('Import failed: ' + (IMPORT_FAILURE_MESSAGES[res?.reason] || res?.reason || 'unknown'));
return;
}
const totalAdded = Object.values(res.added || {}).reduce((a, b) => a + b, 0);
diff --git a/server/lib/README.md b/server/lib/README.md
index 0ce850a0e4..89b163d0a7 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) 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. `requestMaterialization(path, label)` is the fire-and-forget, per-path-deduped `brctl download` read paths kick to heal an evicted file in the background. 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)` 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`. |
| `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 44297d4a34..6eb4b025ab 100644
--- a/server/lib/icloudFile.js
+++ b/server/lib/icloudFile.js
@@ -26,48 +26,124 @@
* 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.
+ * The screen is deliberately scoped to darwin AND paths that resolve into a
+ * cloud-file root. An ordinary APFS file also reports `blocks === 0` when it is
+ * sparse or transparently compressed (data in a `com.apple.decmpfs` xattr), and
+ * other filesystems do the same for inline extents — so an unscoped screen would
+ * refuse to read perfectly good files. Inside a cloud root 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.
+ * **Cost if the screen ever does misfire** (a genuinely sparse or compressed file
+ * that lives inside a cloud root): reads of that file report "temporarily
+ * unavailable" and `brctl download` cannot fix it, because the bytes were never
+ * evicted — so it does NOT self-heal on the next read. Data is never lost: write
+ * paths keep their own refuse-to-overwrite guards, so the failure mode is a
+ * persistent read/write outage for that one file, not corruption. Callers that
+ * must degrade gracefully (a vault walk) skip the file and report a skipped
+ * count; callers that must not silently succeed (a store write) fail loudly.
*/
import { readFile, stat } from 'fs/promises';
+import { realpathSync } from 'fs';
+import { dirname } from 'path';
import { spawn } from 'child_process';
import { createSingleFlight } from './singleFlight.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.
-const UBIQUITY_MARKER = '/Library/Mobile Documents/';
+// macOS cloud-file roots whose contents can be evicted to the cloud and whose
+// first `read(2)` therefore blocks: iCloud's per-app ubiquity containers, and the
+// File Provider mounts macOS 12+ gives third parties (Dropbox / Google Drive /
+// OneDrive "online-only"). `brctl` only heals the iCloud one — but *refusing* the
+// read is what prevents the outage, so both are screened.
+const CLOUD_MARKERS = ['/Library/Mobile Documents/', '/Library/CloudStorage/'];
-/** True when `path` sits inside a macOS iCloud ubiquity container. */
+// Only iCloud paths can be healed with `brctl download`.
+const ICLOUD_MARKER = CLOUD_MARKERS[0];
+
+// A literal substring test is not enough: `~/Documents` is a SYMLINK into
+// `~/Library/Mobile Documents/com~apple~CloudDocs/Documents` when macOS
+// "Desktop & Documents Folders" sync is on, so a vault stored as
+// `/Users/x/Documents/Vault` is in iCloud while its path string says nothing of
+// the sort. Resolving the real path is what closes that hole — but a `realpath`
+// per read would tax every ordinary file read in the process, so resolve the
+// containing DIRECTORY once and memoize it (a vault walk reads many files per
+// directory). Bounded so a long-lived process can't grow it without limit; a
+// symlink that is repointed after boot is not re-resolved until the entry is
+// evicted, which is an acceptable trade for the cost saved.
+const dirCloudCache = new Map();
+const DIR_CACHE_MAX = 512;
+
+function markerMatch(path) {
+ return CLOUD_MARKERS.some(marker => path.includes(marker));
+}
+
+/**
+ * True when `path` resolves into a macOS cloud-file root whose contents can be
+ * evicted. Checks the literal string first (the common, allocation-free case),
+ * then falls back to the memoized real path of the containing directory so a
+ * symlinked route into iCloud (`~/Documents/...`) is still recognized.
+ */
export function isUbiquityPath(path) {
- return typeof path === 'string' && path.includes(UBIQUITY_MARKER);
+ if (typeof path !== 'string' || !path) return false;
+ if (markerMatch(path)) return true;
+ const dir = dirname(path);
+ const cached = dirCloudCache.get(dir);
+ if (cached !== undefined) return cached;
+ // realpathSync throws for a missing/unreadable directory; a path we can't
+ // resolve is not one we can claim is in the cloud.
+ let resolved = false;
+ try {
+ resolved = markerMatch(realpathSync(dir));
+ } catch {
+ resolved = false;
+ }
+ if (dirCloudCache.size >= DIR_CACHE_MAX) dirCloudCache.clear();
+ dirCloudCache.set(dir, resolved);
+ return resolved;
+}
+
+/** True when `path` is an iCloud ubiquity path, the only kind `brctl` can heal. */
+function isHealablePath(path) {
+ if (typeof path !== 'string' || !path) return false;
+ if (path.includes(ICLOUD_MARKER)) return true;
+ try {
+ return realpathSync(dirname(path)).includes(ICLOUD_MARKER);
+ } catch {
+ return false;
+ }
}
/**
* 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()`.
+ * blocks allocated locally.
+ *
+ * **Not sufficient on its own** — an ordinary APFS file reports `blocks === 0`
+ * when it is sparse or transparently compressed, and other filesystems do the
+ * same for inline/compressed extents. Always pair it with the platform + cloud-root
+ * scoping (`isEvictedStats`, or `isSuspectedDataless` which does the `stat` too);
+ * a bare call would refuse to read perfectly good files. Kept exported because a
+ * caller that already holds a `Stats` should not pay a second `stat()`.
*/
export function isDatalessStats(stats) {
return Boolean(stats) && stats.size > 0 && stats.blocks === 0;
}
+/**
+ * The correctly-scoped verdict for a caller that already holds a `Stats`:
+ * dataless-looking AND on darwin AND inside a cloud-file root. Use this rather
+ * than `isDatalessStats` alone.
+ */
+export function isEvictedStats(path, stats) {
+ return process.platform === 'darwin' && isDatalessStats(stats) && isUbiquityPath(path);
+}
+
/**
* True when reading `path` would risk a permanently-blocked `read(2)`. Cheap:
- * one `stat()`, and only on darwin for ubiquity paths. A `stat()` failure
+ * one `stat()`, and only on darwin for cloud-root paths. A `stat()` failure
* (ENOENT/EACCES) resolves `false` — absent and unreadable are the caller's
* existing error paths, not this guard's business.
*/
@@ -101,6 +177,14 @@ const pendingDownloads = new Set();
// later reads pick up where this one stopped.
const MAX_PENDING_DOWNLOADS = 4;
+// Every background download gets a deadline. `brctl` is exactly what hangs when
+// iCloud is wedged — the very condition this module exists for — and without a
+// deadline four hung children would hold all MAX_PENDING_DOWNLOADS slots for the
+// life of the process, silently ending all healing and leaking the children.
+// Exposed (not const) so tests don't wait on it.
+export let DOWNLOAD_DEADLINE_MS = 120_000;
+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
@@ -109,6 +193,10 @@ const MAX_PENDING_DOWNLOADS = 4;
*/
export function requestMaterialization(path, label = 'iCloud file') {
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;
pendingDownloads.add(path);
@@ -127,10 +215,25 @@ export function requestMaterialization(path, label = 'iCloud file') {
console.warn(`⚠️ could not spawn brctl download for ${label}: ${err.message}`);
return false;
}
+ // 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
+ // process alive; the 'exit' handler below clears the slot once the kill lands.
+ 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'); }
+ // A killed-but-unreaped child would strand the slot; drop it now so healing
+ // can resume even if 'exit' never fires.
+ pendingDownloads.delete(path);
+ }, DOWNLOAD_DEADLINE_MS);
+ deadline.unref?.();
+ const settle = () => { clearTimeout(deadline); pendingDownloads.delete(path); };
+
// 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);
+ settle();
if (err.code === 'ENOENT') {
if (markBrctlMissing()) {
console.warn(`⚠️ brctl not found on PATH; ${label} materialization disabled`);
@@ -140,7 +243,7 @@ export function requestMaterialization(path, label = 'iCloud file') {
console.warn(`⚠️ brctl download failed for ${label}: ${err.message}`);
});
child.on('exit', (code, signal) => {
- pendingDownloads.delete(path);
+ settle();
if (code === 0) {
console.log(`📥 ${label} materialized from iCloud: ${path}`);
} else if (code !== null) {
@@ -197,4 +300,5 @@ export function _resetICloudFileStateForTest() {
brctlMissingWarned = false;
pendingDownloads.clear();
readFlight = createSingleFlight();
+ dirCloudCache.clear();
}
diff --git a/server/lib/icloudFile.test.js b/server/lib/icloudFile.test.js
index 355ef3c197..60b234b934 100644
--- a/server/lib/icloudFile.test.js
+++ b/server/lib/icloudFile.test.js
@@ -298,3 +298,107 @@ describe('background-download safety caps', () => {
expect(b64).toBe('body-as-base64');
});
});
+
+describe('cloud-root detection beyond a literal path match', () => {
+ // ~/Documents is a SYMLINK into the CloudDocs ubiquity container when macOS
+ // "Desktop & Documents Folders" sync is on, so a path string can say nothing
+ // about iCloud while the file is very much in it. Real dirs + a real symlink
+ // here: `fs.realpathSync` is not mocked in this suite (only `fs/promises` is).
+ const { mkdtempSync, mkdirSync, symlinkSync, rmSync, writeFileSync } = require('fs');
+ const { tmpdir } = require('os');
+ const { join } = require('path');
+
+ let root, cloudDir, linkDir;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'portos-icloud-link-'));
+ cloudDir = join(root, 'Library', 'Mobile Documents', 'iCloud~md~obsidian', 'Documents', 'Vault');
+ mkdirSync(cloudDir, { recursive: true });
+ writeFileSync(join(cloudDir, 'note.md'), 'x');
+ linkDir = join(root, 'Documents');
+ symlinkSync(join(root, 'Library', 'Mobile Documents', 'iCloud~md~obsidian', 'Documents'), linkDir);
+ });
+
+ afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+ it('recognizes a symlinked route into a ubiquity container', () => {
+ const viaLink = join(linkDir, 'Vault', 'note.md');
+ // The literal string test fails here — only realpath resolution catches it.
+ expect(viaLink.includes('/Library/Mobile Documents/')).toBe(false);
+ expect(icloud.isUbiquityPath(viaLink)).toBe(true);
+ });
+
+ it('guards a read reached through that symlink', async () => {
+ statMock.mockResolvedValue(datalessStats);
+ const viaLink = join(linkDir, 'Vault', 'note.md');
+
+ await expect(icloud.readIfMaterialized(viaLink)).rejects.toMatchObject({
+ code: icloud.ICLOUD_NOT_MATERIALIZED,
+ });
+ // Pre-fix this fell through to a plain readFile — the original hang.
+ expect(readFileMock).not.toHaveBeenCalled();
+ });
+
+ it('still rejects an ordinary directory that resolves nowhere near a cloud root', () => {
+ expect(icloud.isUbiquityPath(join(root, 'plain', 'file.md'))).toBe(false);
+ });
+
+ it('screens ~/Library/CloudStorage (Dropbox/Drive online-only) but does not spawn brctl for it', async () => {
+ statMock.mockResolvedValue(datalessStats);
+ const p = '/Users/example/Library/CloudStorage/Dropbox/Notes/a.md';
+
+ await expect(icloud.readIfMaterialized(p)).rejects.toMatchObject({
+ code: icloud.ICLOUD_NOT_MATERIALIZED,
+ });
+ // Refusing prevents the outage; `brctl` only speaks iCloud, so spawning it
+ // for a third-party File Provider path would be a guaranteed-useless child.
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('isEvictedStats', () => {
+ it('requires a cloud root, not just the dataless-looking numbers', () => {
+ // A sparse or transparently-compressed ordinary file reports blocks:0 with a
+ // real size; treating it as evicted would refuse a readable file forever.
+ expect(icloud.isDatalessStats(datalessStats)).toBe(true);
+ expect(icloud.isEvictedStats(LOCAL_PATH, datalessStats)).toBe(false);
+ expect(icloud.isEvictedStats(ICLOUD_PATH, datalessStats)).toBe(true);
+ });
+
+ it('is false off darwin', () => {
+ platformSpy.mockReturnValue('linux');
+ expect(icloud.isEvictedStats(ICLOUD_PATH, datalessStats)).toBe(false);
+ });
+
+ it('is false for a materialized file in a cloud root', () => {
+ expect(icloud.isEvictedStats(ICLOUD_PATH, materializedStats)).toBe(false);
+ });
+});
+
+describe('background download deadline', () => {
+ it('kills a hung brctl and frees its slot so healing resumes', async () => {
+ const originalDeadline = icloud.DOWNLOAD_DEADLINE_MS;
+ icloud._setDownloadDeadlineForTest(10);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ statMock.mockResolvedValue(datalessStats);
+ // Four children that never exit would otherwise hold every slot forever —
+ // which is exactly what a wedged iCloud does to `brctl`.
+ for (let i = 0; i < 4; i++) {
+ await icloud.readIfMaterialized(`${UBIQUITY_DIR}/hung-${i}.md`).catch(() => {});
+ }
+ expect(spawnMock).toHaveBeenCalledTimes(4);
+ await icloud.readIfMaterialized(`${UBIQUITY_DIR}/blocked.md`).catch(() => {});
+ expect(spawnMock).toHaveBeenCalledTimes(4); // capped, as designed
+
+ await new Promise(r => setTimeout(r, 40)); // let the deadlines fire
+
+ expect(killSpy).toHaveBeenCalled();
+ await icloud.readIfMaterialized(`${UBIQUITY_DIR}/after.md`).catch(() => {});
+ expect(spawnMock).toHaveBeenCalledTimes(5); // slots freed, healing resumed
+ } finally {
+ killSpy.mockRestore();
+ icloud._setDownloadDeadlineForTest(originalDeadline);
+ }
+ });
+});
diff --git a/server/routes/notes.js b/server/routes/notes.js
index e906f06a8e..7c09d38632 100644
--- a/server/routes/notes.js
+++ b/server/routes/notes.js
@@ -91,7 +91,10 @@ router.get('/vaults/:id/scan', asyncHandler(async (req, res) => {
const total = result.notes.length;
const notes = result.notes.slice(offset, offset + limit);
- res.json({ vault: result.vault, notes, total });
+ // Forward the skipped-because-unavailable count (the other readers pass their
+ // whole result through; this one reshapes for pagination and would otherwise
+ // drop it, leaving the client unable to tell a short vault from an offloaded one).
+ res.json({ vault: result.vault, notes, total, skippedUnavailable: result.skippedUnavailable ?? 0 });
}));
router.get('/vaults/:id/note', asyncHandler(async (req, res) => {
diff --git a/server/routes/notes.test.js b/server/routes/notes.test.js
new file mode 100644
index 0000000000..2350c45497
--- /dev/null
+++ b/server/routes/notes.test.js
@@ -0,0 +1,84 @@
+/**
+ * Notes route error mapping — #3704.
+ *
+ * The eviction path added a third class of failure to these handlers: the note
+ * EXISTS but iCloud hasn't downloaded its bytes yet. That is neither a 404 (the
+ * note is not gone) nor a 400 (the request was fine), and the default branch of
+ * `errorStatus` would have made it a 400. It must be 503 so a client can retry.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+vi.mock('../services/obsidian.js', () => ({
+ getNote: vi.fn(),
+ scanVault: vi.fn(),
+}));
+
+const obsidian = await import('../services/obsidian.js');
+const notesRoutes = (await import('./notes.js')).default;
+const { errorMiddleware } = await import('../lib/errorHandler.js');
+
+const app = express();
+app.use(express.json());
+app.use('/api/notes', notesRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => {
+ obsidian.getNote.mockReset();
+ obsidian.scanVault.mockReset();
+});
+
+describe('GET /api/notes/vaults/:id/note error mapping', () => {
+ it('maps NOTE_EVICTED to 503 with a retryable message', async () => {
+ obsidian.getNote.mockResolvedValue({
+ error: 'NOTE_EVICTED',
+ message: 'This note is stored in iCloud and has not been downloaded to this Mac yet.',
+ });
+
+ const res = await request(app).get('/api/notes/vaults/v1/note?path=a.md');
+
+ // 503, not the 400 the default branch would give, and not 404 (it exists).
+ expect(res.status).toBe(503);
+ expect(res.body.code).toBe('NOTE_EVICTED');
+ expect(res.body.error).toMatch(/iCloud/i);
+ });
+
+ it('still maps NOTE_NOT_FOUND to 404', async () => {
+ obsidian.getNote.mockResolvedValue({ error: 'NOTE_NOT_FOUND' });
+ const res = await request(app).get('/api/notes/vaults/v1/note?path=a.md');
+ expect(res.status).toBe(404);
+ expect(res.body.code).toBe('NOTE_NOT_FOUND');
+ });
+
+ it('still maps an unrelated service error to 400', async () => {
+ obsidian.getNote.mockResolvedValue({ error: 'INVALID_PATH', message: 'Path traversal not allowed' });
+ const res = await request(app).get('/api/notes/vaults/v1/note?path=a.md');
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('INVALID_PATH');
+ });
+});
+
+describe('GET /api/notes/vaults/:id/scan', () => {
+ it('forwards skippedUnavailable so a short vault is distinguishable from an offloaded one', async () => {
+ obsidian.scanVault.mockResolvedValue({
+ vault: { id: 'v1', name: 'V' },
+ notes: [{ name: 'a', modifiedAt: new Date().toISOString() }],
+ skippedUnavailable: 7,
+ });
+
+ const res = await request(app).get('/api/notes/vaults/v1/scan');
+
+ expect(res.status).toBe(200);
+ // This handler reshapes for pagination, so the count has to be re-attached
+ // explicitly — it is the one reader that could silently drop it.
+ expect(res.body.skippedUnavailable).toBe(7);
+ });
+
+ it('defaults skippedUnavailable to 0 when the service omits it', async () => {
+ obsidian.scanVault.mockResolvedValue({ vault: { id: 'v1' }, notes: [] });
+ const res = await request(app).get('/api/notes/vaults/v1/scan');
+ expect(res.body.skippedUnavailable).toBe(0);
+ });
+});
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index e9eec32705..eb0eb30c83 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -16,7 +16,7 @@ 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 { ICLOUD_NOT_MATERIALIZED, isEvictedStats, readIfMaterialized, requestMaterialization } from '../lib/icloudFile.js';
import { isPlainObject } from '../lib/objects.js';
import { getSettings, settingsEvents } from './settings.js';
@@ -689,9 +689,15 @@ export async function getStatus() {
// 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);
+ // `isEvictedStats`, not the bare `isDatalessStats`: the dataless signal alone
+ // also matches a sparse/compressed ordinary file, so an unscoped check would
+ // permanently report "unavailable" for a store that `readStore()` is reading
+ // fine. Kick the same background heal the read path does, so a user staring at
+ // the Settings page isn't waiting on some unrelated code path to trigger it.
+ const evicted = isEvictedStats(path, st);
if (evicted) {
console.warn(`⚠️ MortalLoom store evicted from local storage; status summary unavailable: ${path}`);
+ requestMaterialization(path, 'MortalLoom store');
}
const raw = st && !evicted ? await withTransientRetry(() => readIfMaterialized(path, { label: 'MortalLoom store' })).catch((err) => {
if (err.code === 'ENOENT') { readEnoent = true; return null; }
@@ -730,7 +736,12 @@ export async function getStatus() {
/** Non-destructive import: append MortalLoom records missing from PortOS local files. */
export async function importToPortOS() {
- const store = await readStore();
+ // Use the {present, ok} result, not readStore()'s store-or-null: an evicted
+ // store is present-but-unreadable, and reporting it as "file not found" is the
+ // one message most likely to make the user repoint the path or re-seed — burying
+ // the real data this module works to protect.
+ const { present, ok, store } = await readStoreAtPathResult(await resolvePath());
+ if (present && !ok) return { ok: false, reason: 'mortalloom-file-unreadable' };
if (!store) return { ok: false, reason: 'mortalloom-file-not-found' };
const report = { added: {}, skipped: {} };
diff --git a/server/services/obsidian.js b/server/services/obsidian.js
index 760bb6c3d2..326b41347d 100644
--- a/server/services/obsidian.js
+++ b/server/services/obsidian.js
@@ -154,16 +154,24 @@ export async function detectVaults() {
// 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) {
+async function readNoteContent(fullPath, skipped) {
return readIfMaterialized(fullPath, { label: 'Obsidian note' }).catch((err) => {
if (err.code === ICLOUD_NOT_MATERIALIZED) {
console.warn(`⚠️ Obsidian note evicted from local storage; skipping: ${fullPath}`);
+ if (skipped) skipped.count += 1;
return null;
}
throw err;
});
}
+// A vault-wide reader that silently drops evicted notes would report "no results"
+// for a query whose answer is sitting in an un-downloaded note — the exact
+// absent-vs-unavailable collapse the project forbids. Each public reader below
+// therefore carries its own tally and reports `skippedUnavailable` alongside its
+// results, so the UI can say "N notes not downloaded yet" instead of "none".
+const newSkipTally = () => ({ count: 0 });
+
/**
* Scan a vault for markdown files. Reads only frontmatter (not full content)
* for performance. Full content is loaded on individual note reads.
@@ -174,17 +182,18 @@ export async function scanVault(vaultId, { folder } = {}) {
if (!existsSync(vault.path)) return { error: 'PATH_NOT_FOUND' };
const notes = [];
- await walkDir(vault.path, vault.path, notes, folder);
+ const skipped = newSkipTally();
+ await walkDir(vault.path, vault.path, notes, folder, skipped);
notes.sort((a, b) => new Date(b.modifiedAt) - new Date(a.modifiedAt));
- return { vault, notes, total: notes.length };
+ return { vault, notes, total: notes.length, skippedUnavailable: skipped.count };
}
/**
* Light scan: reads only file stats and first ~1KB for frontmatter/tags.
* Skips full content parsing for performance on large vaults.
*/
-async function walkDir(rootPath, currentPath, results, folderFilter) {
+async function walkDir(rootPath, currentPath, results, folderFilter, skipped) {
const entries = await readdir(currentPath, { withFileTypes: true });
for (const entry of entries) {
@@ -192,7 +201,7 @@ async function walkDir(rootPath, currentPath, results, folderFilter) {
const fullPath = join(currentPath, entry.name);
if (entry.isDirectory()) {
- await walkDir(rootPath, fullPath, results, folderFilter);
+ await walkDir(rootPath, fullPath, results, folderFilter, skipped);
} else if (entry.isFile() && extname(entry.name) === '.md') {
const relativePath = relative(rootPath, fullPath);
const noteFolder = dirname(relativePath) === '.' ? '' : dirname(relativePath);
@@ -205,7 +214,7 @@ 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 readNoteContent(fullPath);
+ const fd = await readNoteContent(fullPath, skipped);
if (fd === null) continue;
const header = fd.length > 2048 ? fd.slice(0, 2048) : fd;
const { frontmatter, tags } = parseNoteMetadata(header);
@@ -362,7 +371,8 @@ export async function searchNotes(vaultId, query) {
const queryLower = query.toLowerCase();
// Compile regex once for count matching
const countRe = new RegExp(escapeRegex(queryLower), 'g');
- await searchDir(vault.path, vault.path, queryLower, countRe, results);
+ const skipped = newSkipTally();
+ await searchDir(vault.path, vault.path, queryLower, countRe, results, skipped);
results.sort((a, b) => {
if (a.titleMatch && !b.titleMatch) return -1;
@@ -370,10 +380,10 @@ export async function searchNotes(vaultId, query) {
return b.matchCount - a.matchCount;
});
- return { results, total: results.length, query };
+ return { results, total: results.length, query, skippedUnavailable: skipped.count };
}
-async function searchDir(rootPath, currentPath, query, countRe, results) {
+async function searchDir(rootPath, currentPath, query, countRe, results, skipped) {
const entries = await readdir(currentPath, { withFileTypes: true });
// Kick off this directory's markdown reads concurrently (the disk-latency
@@ -384,7 +394,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, readNoteContent(join(currentPath, entry.name)));
+ contentReads.set(entry.name, readNoteContent(join(currentPath, entry.name), skipped));
}
}
@@ -393,7 +403,7 @@ async function searchDir(rootPath, currentPath, query, countRe, results) {
const fullPath = join(currentPath, entry.name);
if (entry.isDirectory()) {
- await searchDir(rootPath, fullPath, query, countRe, results);
+ await searchDir(rootPath, fullPath, query, countRe, results, skipped);
} 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
@@ -443,7 +453,8 @@ export async function getVaultGraph(vaultId) {
const edges = [];
const noteMap = new Map();
- await collectNotes(vault.path, vault.path, noteMap, nodes);
+ const skipped = newSkipTally();
+ await collectNotes(vault.path, vault.path, noteMap, nodes, skipped);
// Build case-insensitive lookup for wikilink resolution
const lowerMap = new Map();
@@ -464,11 +475,14 @@ export async function getVaultGraph(vaultId) {
nodes: nodes.map(({ path, name, folder, tags }) => ({ path, name, folder, tags })),
edges,
totalNodes: nodes.length,
- totalEdges: edges.length
+ totalEdges: edges.length,
+ // Evicted notes are missing from the graph entirely — and so is every edge
+ // into them, which would otherwise render a wrong topology as authoritative.
+ skippedUnavailable: skipped.count
};
}
-async function collectNotes(rootPath, currentPath, noteMap, nodes) {
+async function collectNotes(rootPath, currentPath, noteMap, nodes, skipped) {
const entries = await readdir(currentPath, { withFileTypes: true });
// Read this directory's markdown files concurrently, but apply them in the
@@ -479,7 +493,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, readNoteContent(join(currentPath, entry.name)));
+ contentReads.set(entry.name, readNoteContent(join(currentPath, entry.name), skipped));
}
}
@@ -488,7 +502,7 @@ async function collectNotes(rootPath, currentPath, noteMap, nodes) {
const fullPath = join(currentPath, entry.name);
if (entry.isDirectory()) {
- await collectNotes(rootPath, fullPath, noteMap, nodes);
+ await collectNotes(rootPath, fullPath, noteMap, nodes, skipped);
} 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
@@ -608,6 +622,9 @@ async function findBacklinksInDir(rootPath, currentPath, targetLower, results) {
if (entry.isDirectory()) {
await findBacklinksInDir(rootPath, fullPath, targetLower, results);
} else if (entry.isFile() && extname(entry.name) === '.md') {
+ // findBacklinks is supplementary to a note that already loaded, so an
+ // evicted neighbour is logged by readNoteContent but not surfaced as a
+ // count — the note itself is not misreported as empty.
const content = await readNoteContent(fullPath);
if (content === null) continue; // evicted from iCloud — skip, don't block
WIKILINK_RE.lastIndex = 0;
@@ -631,16 +648,17 @@ export async function getVaultTags(vaultId) {
if (!existsSync(vault.path)) return { error: 'PATH_NOT_FOUND' };
const tagCounts = new Map();
- await collectTags(vault.path, vault.path, tagCounts);
+ const skipped = newSkipTally();
+ await collectTags(vault.path, vault.path, tagCounts, skipped);
const tags = [...tagCounts.entries()]
.map(([tag, count]) => ({ tag, count }))
.sort((a, b) => b.count - a.count);
- return { tags, total: tags.length };
+ return { tags, total: tags.length, skippedUnavailable: skipped.count };
}
-async function collectTags(rootPath, currentPath, tagCounts) {
+async function collectTags(rootPath, currentPath, tagCounts, skipped) {
const entries = await readdir(currentPath, { withFileTypes: true });
for (const entry of entries) {
@@ -648,9 +666,9 @@ async function collectTags(rootPath, currentPath, tagCounts) {
const fullPath = join(currentPath, entry.name);
if (entry.isDirectory()) {
- await collectTags(rootPath, fullPath, tagCounts);
+ await collectTags(rootPath, fullPath, tagCounts, skipped);
} else if (entry.isFile() && extname(entry.name) === '.md') {
- const content = await readNoteContent(fullPath);
+ const content = await readNoteContent(fullPath, skipped);
if (content === null) continue; // evicted from iCloud — skip, don't block
const { tags } = parseNoteMetadata(content);
for (const tag of tags) {
diff --git a/server/services/obsidianEvicted.test.js b/server/services/obsidianEvicted.test.js
new file mode 100644
index 0000000000..36e0873fa7
--- /dev/null
+++ b/server/services/obsidianEvicted.test.js
@@ -0,0 +1,112 @@
+/**
+ * Obsidian readers against an EVICTED (iCloud-offloaded) note — #3704.
+ *
+ * Kept separate from `obsidian.test.js` because that suite deliberately runs
+ * against a real temp vault with no mocks; here `../lib/icloudFile.js` is mocked
+ * so one specific note behaves as evicted while its neighbours read normally.
+ *
+ * What this pins: an evicted note must never be *silently* dropped. Before the
+ * guard, reading one blocked the process forever; the guard makes the read fail
+ * fast, and the risk that replaces the hang is a vault-wide reader reporting
+ * "no results" for a query whose answer sits in an un-downloaded note. Each
+ * reader therefore reports a `skippedUnavailable` count, and `getNote` reports
+ * NOTE_EVICTED rather than NOTE_NOT_FOUND.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdirSync, rmSync, writeFileSync } from 'fs';
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const tempRoot = createTempDataRoot('portos-obsidian-evicted-');
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: tempRoot });
+});
+
+// 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".
+vi.mock('../lib/icloudFile.js', () => ({
+ ICLOUD_NOT_MATERIALIZED: 'ICLOUD_NOT_MATERIALIZED',
+ readIfMaterialized: vi.fn(async (path) => {
+ if (path.endsWith('evicted.md')) {
+ throw Object.assign(new Error('evicted'), { code: 'ICLOUD_NOT_MATERIALIZED' });
+ }
+ return readFile(path, 'utf-8');
+ }),
+}));
+
+const { addVault, scanVault, searchNotes, getVaultTags, getVaultGraph, getNote } =
+ await import('./obsidian.js');
+
+const VAULT_DIR = join(tempRoot, 'vault');
+let vaultId;
+
+beforeEach(async () => {
+ rmSync(tempRoot, { recursive: true, force: true });
+ mkdirSync(join(VAULT_DIR, '.obsidian'), { recursive: true });
+ // `readable.md` and `evicted.md` both match the search term and share a tag, so
+ // every reader below has exactly one skipped note and one real hit.
+ writeFileSync(join(VAULT_DIR, 'readable.md'), '---\ntags: [biology]\n---\nmitochondria here\n[[evicted]]\n');
+ writeFileSync(join(VAULT_DIR, 'evicted.md'), '---\ntags: [biology, offloaded]\n---\nmitochondria there too\n');
+ const vault = await addVault({ name: 'Test Vault', path: VAULT_DIR });
+ vaultId = vault.id;
+});
+
+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));
+
+describe('obsidian readers with an evicted note', () => {
+ it('scanVault skips the evicted note and reports the count', async () => {
+ const result = await scanVault(vaultId);
+ expect(result.notes.map(n => n.name)).toEqual(['readable']);
+ expect(result.skippedUnavailable).toBe(1);
+ });
+
+ it('searchNotes reports skipped notes instead of implying no match exists', async () => {
+ const result = await searchNotes(vaultId, 'mitochondria');
+ // The term is in BOTH notes; only the readable one can be reported.
+ expect(result.results).toHaveLength(1);
+ expect(result.results[0].name).toBe('readable');
+ // Without this the UI renders a bare "No/1 results" and the user concludes
+ // the other note doesn't contain the term.
+ expect(result.skippedUnavailable).toBe(1);
+ });
+
+ it('getVaultTags under-counts visibly, not silently', async () => {
+ const result = await getVaultTags(vaultId);
+ const biology = result.tags.find(t => t.tag === 'biology');
+ expect(biology.count).toBe(1); // 2 notes carry it; 1 is unreadable
+ expect(result.tags.find(t => t.tag === 'offloaded')).toBeUndefined();
+ expect(result.skippedUnavailable).toBe(1);
+ });
+
+ it('getVaultGraph drops the evicted node and says so', async () => {
+ const result = await getVaultGraph(vaultId);
+ expect(result.nodes.map(n => n.name)).toEqual(['readable']);
+ // The [[evicted]] wikilink can't resolve to a node that was never collected,
+ // so the edge silently vanishes too — hence the count.
+ expect(result.edges).toHaveLength(0);
+ expect(result.skippedUnavailable).toBe(1);
+ });
+
+ it('getNote reports NOTE_EVICTED, not NOTE_NOT_FOUND', async () => {
+ const result = await getNote(vaultId, 'evicted.md');
+ // NOTE_NOT_FOUND would tell the user a note they can see in Obsidian is gone.
+ expect(result.error).toBe('NOTE_EVICTED');
+ expect(result.message).toMatch(/iCloud/i);
+ });
+
+ it('getNote still reads a materialized note normally', async () => {
+ const result = await getNote(vaultId, 'readable.md');
+ expect(result.error).toBeUndefined();
+ expect(result.content).toContain('mitochondria');
+ });
+
+ it('a non-eviction read error still propagates (not swallowed as a skip)', async () => {
+ const { readIfMaterialized } = await import('../lib/icloudFile.js');
+ readIfMaterialized.mockRejectedValueOnce(Object.assign(new Error('boom'), { code: 'EIO' }));
+ await expect(getNote(vaultId, 'readable.md')).rejects.toThrow('boom');
+ });
+});