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

refactor([issue-3704]): reuse the shared single-flight helper, drop speculative API

Adam Eivydfb5ce62d432
diff --git a/server/lib/README.md b/server/lib/README.md
index 655c1207b5..0ce850a0e4 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. `materializeICloudFile(path, {timeoutMs, label})` is the awaited, timeout-bounded `brctl download` for **write** paths that must know the bytes are local before overwriting; `requestMaterialization(path, label)` is the fire-and-forget, per-path-deduped form read paths use. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. |
+| `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`. |
| `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 e867d3bd9b..d6e0f36c4e 100644
--- a/server/lib/icloudFile.js
+++ b/server/lib/icloudFile.js
@@ -43,16 +43,13 @@
import { readFile, stat } from 'fs/promises';
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. */
export const ICLOUD_NOT_MATERIALIZED = 'ICLOUD_NOT_MATERIALIZED';
-/** Every macOS app ubiquity container lives under this path segment. */
-export const UBIQUITY_MARKER = '/Library/Mobile Documents/';
-
-/** Default bound on an awaited `brctl download` (write paths only). */
-export const DEFAULT_MATERIALIZE_TIMEOUT_MS = 20000;
+// Every macOS app ubiquity container lives under this path segment.
+const UBIQUITY_MARKER = '/Library/Mobile Documents/';
/** True when `path` sits inside a macOS iCloud ubiquity container. */
export function isUbiquityPath(path) {
@@ -85,8 +82,8 @@ export async function isSuspectedDataless(path) {
// materialization is a silent no-op, without spamming on every read.
let brctlMissingWarned = false;
-/** Claim the one-shot "brctl is missing" warning. True on the first call only. */
-export function markBrctlMissing() {
+// Claim the one-shot "brctl is missing" warning. True on the first call only.
+function markBrctlMissing() {
if (brctlMissingWarned) return false;
brctlMissingWarned = true;
return true;
@@ -147,41 +144,11 @@ export function requestMaterialization(path, label = 'iCloud file') {
return true;
}
-/**
- * Awaited `brctl download <path>`, bounded by `timeoutMs`. For **write** paths
- * that must know whether the bytes are local before deciding it's safe to
- * overwrite. Resolves `true` only on a clean exit-0; every failure mode
- * (non-darwin, missing brctl, spawn error, timeout, non-zero exit) resolves
- * `false` so the caller falls through to its own refuse-to-overwrite guard —
- * this can only improve the situation, never worsen it.
- *
- * Read paths must NOT use this: a wedged iCloud makes every read pay the full
- * timeout. They use `requestMaterialization` (background) instead.
- */
-export async function materializeICloudFile(path, options = {}) {
- const { timeoutMs = DEFAULT_MATERIALIZE_TIMEOUT_MS, label = 'iCloud file' } = options;
- if (process.platform !== 'darwin' || !path) return false;
- const result = await bufferedSpawn('brctl', ['download', path], { timeoutMs, shell: false });
- if (result.success) return true;
- if (result.error?.code === 'ENOENT') {
- if (markBrctlMissing()) {
- console.warn(`⚠️ brctl not found on PATH; ${label} on-demand materialize disabled`);
- }
- } else if (result.timedOut) {
- console.warn(`⚠️ brctl download timed out after ${timeoutMs}ms for ${label}: ${path}`);
- } else if (result.error) {
- console.warn(`⚠️ brctl download failed for ${label}: ${result.error.message}`);
- } else {
- console.warn(`⚠️ brctl download exited ${result.code} for ${label}: ${path}`);
- }
- return false;
-}
-
-// Single-flight map so N concurrent callers for the same path share ONE
-// underlying read and can occupy at most one threadpool slot between them.
-// Entries are removed as soon as the read settles, so a later call re-reads
-// (this coalesces concurrency, it does not cache content).
-const inFlightReads = new Map();
+// 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
+// coalesces concurrency, it does not cache content.
+let readFlight = createSingleFlight();
/**
* `readFile`, but never against an evicted iCloud file.
@@ -200,11 +167,7 @@ const inFlightReads = new Map();
* doesn't starve the process.
*/
export async function readIfMaterialized(path, options = {}) {
- const existing = inFlightReads.get(path);
- if (existing) return existing;
- const pending = guardedRead(path, options).finally(() => inFlightReads.delete(path));
- inFlightReads.set(path, pending);
- return pending;
+ return readFlight.run(path, () => guardedRead(path, options));
}
async function guardedRead(path, options) {
@@ -222,5 +185,5 @@ async function guardedRead(path, options) {
export function _resetICloudFileStateForTest() {
brctlMissingWarned = false;
pendingDownloads.clear();
- inFlightReads.clear();
+ readFlight = createSingleFlight();
}
diff --git a/server/lib/icloudFile.test.js b/server/lib/icloudFile.test.js
index 7fc44664da..ce10cc6408 100644
--- a/server/lib/icloudFile.test.js
+++ b/server/lib/icloudFile.test.js
@@ -6,7 +6,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
const statMock = vi.fn();
const readFileMock = vi.fn();
const spawnMock = vi.fn();
-const bufferedSpawnMock = vi.fn();
vi.mock('fs/promises', () => ({
stat: (...args) => statMock(...args),
@@ -17,10 +16,6 @@ vi.mock('child_process', () => ({
spawn: (...args) => spawnMock(...args),
}));
-vi.mock('./bufferedSpawn.js', () => ({
- bufferedSpawn: (...args) => bufferedSpawnMock(...args),
-}));
-
const UBIQUITY_DIR = '/Users/example/Library/Mobile Documents/iCloud~com~example~App/Documents';
const ICLOUD_PATH = `${UBIQUITY_DIR}/Store.json`;
const LOCAL_PATH = '/Users/example/projects/app/data/store.json';
@@ -49,7 +44,6 @@ beforeEach(async () => {
statMock.mockReset();
readFileMock.mockReset();
spawnMock.mockReset();
- bufferedSpawnMock.mockReset();
// The guard is macOS-only; pin the platform so the suite is deterministic on
// Linux CI as well as a developer Mac.
platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');
@@ -263,41 +257,3 @@ describe('requestMaterialization', () => {
expect(spawnMock).not.toHaveBeenCalled();
});
});
-
-describe('materializeICloudFile', () => {
- it('resolves true on a clean brctl exit', async () => {
- bufferedSpawnMock.mockResolvedValue({ success: true, code: 0 });
- await expect(icloud.materializeICloudFile(ICLOUD_PATH)).resolves.toBe(true);
- expect(bufferedSpawnMock).toHaveBeenCalledWith(
- 'brctl',
- ['download', ICLOUD_PATH],
- expect.objectContaining({ shell: false })
- );
- });
-
- it('resolves false (never throws) on a timeout, so the caller keeps its own guard', async () => {
- bufferedSpawnMock.mockResolvedValue({ success: false, code: -1, timedOut: true });
- await expect(icloud.materializeICloudFile(ICLOUD_PATH, { timeoutMs: 50 })).resolves.toBe(false);
- });
-
- it('resolves false on a non-zero exit', async () => {
- bufferedSpawnMock.mockResolvedValue({ success: false, code: 1, timedOut: false });
- await expect(icloud.materializeICloudFile(ICLOUD_PATH)).resolves.toBe(false);
- });
-
- it('honors the caller-supplied timeout', async () => {
- bufferedSpawnMock.mockResolvedValue({ success: true, code: 0 });
- await icloud.materializeICloudFile(ICLOUD_PATH, { timeoutMs: 1234 });
- expect(bufferedSpawnMock).toHaveBeenCalledWith(
- 'brctl',
- expect.any(Array),
- expect.objectContaining({ timeoutMs: 1234 })
- );
- });
-
- it('is a no-op off darwin', async () => {
- platformSpy.mockReturnValue('linux');
- await expect(icloud.materializeICloudFile(ICLOUD_PATH)).resolves.toBe(false);
- expect(bufferedSpawnMock).not.toHaveBeenCalled();
- });
-});