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-3705]): address claude review — deadline onFailure once-guard, direct option tests, doc accuracy

Adam Eivy6c17e65e78b8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9df926fecc..6b7dc26e08 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,7 +4,7 @@
- **[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.
+- 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 503f7d1b7a..736c70704a 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 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`. |
+| `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`. |
| `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 111034bd33..2f95573bc8 100644
--- a/server/lib/icloudFile.js
+++ b/server/lib/icloudFile.js
@@ -207,7 +207,7 @@ export function _setDownloadDeadlineForTest(ms) { DOWNLOAD_DEADLINE_MS = ms; }
* @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
+ * pass `true`: the request is tracked in the shared in-flight map (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
@@ -256,6 +256,20 @@ export function requestMaterialization(path, options = {}) {
const release = () => {
if (retryAfterExit && pendingDownloads.get(path) === child) pendingDownloads.delete(path);
};
+ // Notify the caller's failure hook AT MOST once per child. `'error'` may be
+ // followed by `'exit'` (Node makes no guarantee either way), and the deadline
+ // handler below fires it too — a child that is SIGKILL'd but never reaped emits
+ // no `'exit'`, so without invoking it from the deadline an untracked (pin)
+ // caller's sticky dedupe would stay set forever and never re-pin. The once-guard
+ // means a stale child's late `'exit'` can't fire the hook a second time and
+ // clear a live replacement child's sticky path (both share the same `path`, so
+ // the hook's own path guard can't tell them apart).
+ let failureNotified = false;
+ const notifyFailure = () => {
+ if (failureNotified) return;
+ failureNotified = true;
+ onFailure?.();
+ };
// 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.
@@ -264,12 +278,14 @@ export function requestMaterialization(path, options = {}) {
// The child is detached (its own process group), so a bare kill would leave
// 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.
+ // here would crash the process with no `next(err)` to catch it, and `child`
+ // may not be a real ChildProcess with a `kill` method (e.g. a test double).
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.
+ // A killed-but-unreaped child would strand the slot AND (for an untracked pin)
+ // leave the sticky dedupe set forever; drop both now so healing can resume even
+ // if 'exit' never fires.
release();
+ notifyFailure();
}, DOWNLOAD_DEADLINE_MS);
deadline.unref?.();
const settle = () => { clearTimeout(deadline); release(); };
@@ -278,7 +294,7 @@ export function requestMaterialization(path, options = {}) {
// dedupe entry for a different path.
child.on('error', (err) => {
settle();
- onFailure?.();
+ notifyFailure();
if (err.code === 'ENOENT') {
if (claimBrctlMissingWarning()) {
console.warn(`⚠️ brctl not found on PATH; ${label} materialization disabled`);
@@ -293,7 +309,7 @@ export function requestMaterialization(path, options = {}) {
console.log(`📥 ${label} materialized from iCloud: ${path}`);
return;
}
- onFailure?.();
+ notifyFailure();
if (code !== null) {
console.warn(`⚠️ brctl download exited ${code} for ${label}: ${path}`);
} else {
diff --git a/server/lib/icloudFile.test.js b/server/lib/icloudFile.test.js
index a27b7db99e..10934413c8 100644
--- a/server/lib/icloudFile.test.js
+++ b/server/lib/icloudFile.test.js
@@ -256,6 +256,80 @@ describe('requestMaterialization', () => {
expect(icloud.requestMaterialization(ICLOUD_PATH)).toBe(false);
expect(spawnMock).not.toHaveBeenCalled();
});
+
+ // The pin path (mortalLoomStore) passes retryAfterExit:false: it owns its own
+ // single-sticky-path dedupe, so the shared helper must NOT dedupe it in the
+ // in-flight map, must NOT count it against the concurrency cap, and must route
+ // its failures through onFailure so the pin can clear its sticky path.
+ describe('retryAfterExit:false (the pin path)', () => {
+ it('does not dedupe on the in-flight map — a second call for the same path spawns again', () => {
+ spawnMock.mockImplementation(() => makeFakeChild());
+ expect(icloud.requestMaterialization(ICLOUD_PATH, { retryAfterExit: false })).toBe(true);
+ expect(icloud.requestMaterialization(ICLOUD_PATH, { retryAfterExit: false })).toBe(true);
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('neither consumes a concurrency slot nor is blocked by the cap', async () => {
+ statMock.mockResolvedValue(datalessStats);
+ // Fill all four tracked (read) slots with in-flight downloads.
+ for (let i = 0; i < 4; i++) {
+ await icloud.readIfMaterialized(`${UBIQUITY_DIR}/read-${i}.md`).catch(() => {});
+ }
+ expect(spawnMock).toHaveBeenCalledTimes(4);
+ // An untracked (pin) request still spawns even though the cap is full…
+ expect(icloud.requestMaterialization(`${UBIQUITY_DIR}/pin.json`, { retryAfterExit: false })).toBe(true);
+ expect(spawnMock).toHaveBeenCalledTimes(5);
+ // …and it did NOT occupy a slot: a fresh tracked read for a new path is
+ // still refused because the four read slots remain full.
+ await icloud.readIfMaterialized(`${UBIQUITY_DIR}/read-blocked.md`).catch(() => {});
+ expect(spawnMock).toHaveBeenCalledTimes(5);
+ });
+
+ it('fires onFailure on a non-zero exit, a signal-kill, and an error — never on exit 0', () => {
+ const runOne = (emit) => {
+ const child = makeFakeChild();
+ spawnMock.mockReturnValueOnce(child);
+ const onFailure = vi.fn();
+ icloud.requestMaterialization(ICLOUD_PATH, { retryAfterExit: false, onFailure });
+ emit(child);
+ return onFailure;
+ };
+ expect(runOne((c) => c.emit('exit', 0, null))).not.toHaveBeenCalled();
+ expect(runOne((c) => c.emit('exit', 1, null))).toHaveBeenCalledTimes(1);
+ expect(runOne((c) => c.emit('exit', null, 'SIGKILL'))).toHaveBeenCalledTimes(1);
+ expect(runOne((c) => c.emit('error', Object.assign(new Error('boom'), { code: 'EAGAIN' })))).toHaveBeenCalledTimes(1);
+ });
+
+ it('fires onFailure at most once even if error is followed by exit', () => {
+ const child = makeFakeChild();
+ spawnMock.mockReturnValue(child);
+ const onFailure = vi.fn();
+ icloud.requestMaterialization(ICLOUD_PATH, { retryAfterExit: false, onFailure });
+ child.emit('error', Object.assign(new Error('boom'), { code: 'EAGAIN' }));
+ child.emit('exit', null, 'SIGKILL');
+ expect(onFailure).toHaveBeenCalledTimes(1);
+ });
+
+ it('fires onFailure when the deadline kills a hung child that never exits', async () => {
+ const originalDeadline = icloud.DOWNLOAD_DEADLINE_MS;
+ icloud._setDownloadDeadlineForTest(10);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ try {
+ const child = makeFakeChild();
+ child.pid = 5150;
+ spawnMock.mockReturnValue(child);
+ const onFailure = vi.fn();
+ icloud.requestMaterialization(ICLOUD_PATH, { retryAfterExit: false, onFailure });
+ // The child never emits 'exit'; only the deadline can clear the sticky path.
+ await new Promise((r) => setTimeout(r, 30));
+ expect(killSpy).toHaveBeenCalled();
+ expect(onFailure).toHaveBeenCalledTimes(1);
+ } finally {
+ killSpy.mockRestore();
+ icloud._setDownloadDeadlineForTest(originalDeadline);
+ }
+ });
+ });
});
describe('background-download safety caps', () => {
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index 6c3870762a..e04b1337ff 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -107,7 +107,7 @@ let lastPinnedPath = null;
// 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
+// the pin in its in-flight read-heal map. `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.