Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (claude): correct the measurement's provenance and the stale README row
[._.]/ Adam Eivyfbd3100d922b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex eae78e19e8..7ceed6ccc5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -191,7 +191,7 @@## Internal-- **[issue-3713] Confirmed that deleting an iCloud-offloaded note is safe, and pinned the decision not to guard it.** [issue-3706] proved that *overwriting* an offloaded file stalls in the kernel exactly like reading one, which left `obsidian.deleteNote`'s `unlink` as the last unguarded write-shaped call on the vault adapter. The POSIX argument ("unlink only drops a directory entry, so there is nothing to download") was not safe to lean on — `link` is pure metadata too and it *does* materialize, and [issue-3706]'s whole lesson was that the intuitive answer about `O_TRUNC` was wrong. Measured instead, on freshly-evicted iCloud fixtures with each syscall timed in a killable child process: `unlink` returned in 0.1 ms at both 512 KB and 5 MB, three runs of three, against 884 ms to `read` the same dataless 5 MB file. So no guard — and not merely because it is unnecessary: the [issue-3706] remedy is to download the file and wait, which here would mean fetching every byte of a note purely to throw it away. A test now pins the *absence* of the screen so a later "add it for symmetry" change has to argue with it. The syscall table in `server/lib/icloudFile.js` gained the `unlink` row.+- **[issue-3713] Confirmed that deleting an iCloud-offloaded note is safe, and pinned the decision not to guard it.** [issue-3706] proved that *overwriting* an offloaded file stalls in the kernel exactly like reading one, which left `obsidian.deleteNote`'s `unlink` as the last unguarded write-shaped call on the vault adapter. The POSIX argument ("unlink only drops a directory entry, so there is nothing to download") was not safe to lean on — `link` is pure metadata too and it *does* materialize, and [issue-3706]'s whole lesson was that the intuitive answer about `O_TRUNC` was wrong. Measured instead, on freshly-evicted iCloud fixtures with each syscall timed in a killable child process: `unlink` returned in 0.1 ms across three runs (two at 512 KB, one at 5 MB), against 884 ms to `read` a separate, equally-sized 5 MB dataless file. So no guard — and not merely because it is unnecessary: the [issue-3706] remedy is to download the file and wait, which here would mean fetching every byte of a note purely to throw it away. A test now pins the *absence* of the screen so a later "add it for symmetry" change has to argue with it. The syscall table in `server/lib/icloudFile.js` gained the `unlink` row.- Internal: [issue-3713] `brctl evict <path>` turns out to work, correcting a note carried by [issue-3706] and [issue-3716] that recorded programmatic eviction as unavailable to an unentitled CLI (leaving a manual Finder step as the only route). Like `brctl download` it is absent from `brctl --help` but fully functional, refusing only when run as root. That makes the whole evict/measure/heal loop scriptable, so the next iCloud syscall question can be answered without a human at the keyboard; the recipe, and the tooling that genuinely does not work (`fileproviderctl`, `chflags dataless`, `FileManager.evictUbiquitousItem`), is now a section in `server/lib/icloudFile.js`.diff --git a/server/lib/README.md b/server/lib/README.mdindex 46ba38e183..a00f0a7ce8 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 **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`. |+| `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, #3713), and recorded in the module docblock's syscall table: `stat`/`open`/`rename`/`unlink` never materialize, while `read`, `write` (including after `O_TRUNC` — truncating does NOT skip the download), `link`, and `clonefile` all do. `unlink` being free is a measurement, not the POSIX inference — `link` is pure metadata too and it *does* materialize — so delete paths need no screen. The docblock also carries the reproduction recipe: `brctl evict <path>` works (undocumented, like `brctl download`), which is what makes the evict/measure/heal loop scriptable. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. || `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |diff --git a/server/lib/icloudFile.js b/server/lib/icloudFile.jsindex 4f3fd1abe3..2b77214be4 100644--- a/server/lib/icloudFile.js+++ b/server/lib/icloudFile.js@@ -54,19 +54,22 @@* "Unlink only drops a directory entry, so there is nothing to download" is* the same shape of argument as the `O_TRUNC` one above, and `link` is pure* metadata too yet it *does* materialize. Measured instead: `unlinkSync` on a- * freshly-evicted file returned in **0.1 ms** at both 512 KB and 5 MB — three- * runs of three — against **884 ms** for a `read` of the same 5 MB dataless- * fixture, and no download was issued. So delete paths need no screen.+ * freshly-evicted file returned in **0.1 ms** across three runs — two at+ * 512 KB, one at 5 MB — against **884 ms** to `read` a separate, equally-sized+ * 5 MB dataless fixture, and no download was issued. So delete paths need no+ * screen.** ## Reproducing these measurements** Eviction is the hard part, and it is NOT unavailable to a CLI: `brctl evict- * <path>` works and is the mechanism used for all of the above. Like `brctl- * download` (which the heal path below uses) it is absent from `brctl --help`- * but fully functional; it refuses only when run as root. Everything else that- * looks like it should work does not — `fileproviderctl` has no `evict`,- * `chflags dataless` silently no-ops, and `FileManager.evictUbiquitousItem`- * fails `NSCocoaErrorDomain 512` from an unentitled process. Verify the state+ * <path>` works. It is the mechanism behind the `unlink` row (#3713); the rows+ * above it were measured before `brctl evict` was known to work, by evicting+ * through Finder's "Remove Download". Like `brctl download` (which the heal path+ * below uses) it is absent from `brctl --help` but fully functional; it refuses+ * only when run as root. Everything else that looks like it should work does+ * not — `fileproviderctl` has no `evict`, `chflags dataless` silently no-ops,+ * and `FileManager.evictUbiquitousItem` fails `NSCocoaErrorDomain 512` from an+ * unentitled process. Verify the state* with `stat -f "blocks=%b flags=%Sf size=%z"`: evicted reads `blocks=0` and* `compressed,dataless`. Always time the syscall in a CHILD process with a hard* kill — a materialization that stalls cannot be cancelled — and use a freshdiff --git a/server/services/obsidian.js b/server/services/obsidian.jsindex de9ae9cef3..b8433af002 100644--- a/server/services/obsidian.js+++ b/server/services/obsidian.js@@ -396,8 +396,10 @@ export async function deleteNote(vaultId, notePath) {// an evicted vnode. That is measured, not inferred from POSIX — `link` is pure// metadata too and it *does* materialize, so the analogy with `rename` was not// safe to lean on. On a freshly-evicted iCloud file `unlinkSync` returned in- // 0.1 ms at both 512 KB and 5 MB, versus 884 ms to `read` the same 5 MB- // dataless fixture. Deleting an offloaded note therefore cannot wedge the libuv+ // 0.1 ms across three runs (two at 512 KB, one at 5 MB), versus 884 ms to+ // `read` a separate, equally-sized 5 MB dataless fixture — a fresh subject per+ // case, since the first materializing call heals the file. Deleting an+ // offloaded note therefore cannot wedge the libuv// threadpool the way `updateNote`'s overwrite could, and guarding it would be// strictly worse than useless: the guard's own remedy is `materializeAndWait`,// i.e. downloading every byte of a file purely to throw it away.diff --git a/server/services/obsidianEvicted.test.js b/server/services/obsidianEvicted.test.jsindex 3c98b04873..a99e397c5c 100644--- a/server/services/obsidianEvicted.test.js+++ b/server/services/obsidianEvicted.test.js@@ -232,8 +232,9 @@ describe('obsidian updateNote against an evicted note', () => {** `deleteNote` was the third candidate for the #3706 treatment, on the theory* that `unlink` might materialize the way `link` does. Measured: it does not- * (0.1 ms dataless at 512 KB and 5 MB, vs 884 ms to read the same 5 MB dataless- * fixture), so the correct outcome is *no guard*. These pin that absence — a+ * (0.1 ms dataless across three runs — two at 512 KB, one at 5 MB — vs 884 ms to+ * read a separate 5 MB dataless fixture), so the correct outcome is *no guard*.+ * These pin that absence — a* "for symmetry with updateNote" change has to argue with a test, because the* guard it would add is actively harmful: `materializeAndWait` would download* the whole file just to unlink it.