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
fix(universe-builder): serialize writes via shared file-write queue (#282)
[._.]/ Adam Eivyb3a9d12d19f9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 761e6dd480..9bb9f94d23 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -21,6 +21,7 @@## Fixed+- **Universe Builder writes are now serialized server-side so concurrent PATCHes can't clobber each other.** `createUniverse` / `updateUniverse` / `insertUniverseWithId` / `deleteUniverse` / `recordRun` all share the same `data/universe-builder.json` file. Without serialization, two near-simultaneous saves (e.g. an auto-save plus a "Promote variation" race, or two browser tabs editing different fields) each computed their merged state from the same pre-write snapshot — last write wins, the other change silently disappears. Each mutating call now enqueues onto a single file-level write tail so every write reads the freshest persisted state. Per CLAUDE.md "Async PATCH races on shared records — serialize writes server-side"; the queue is single-tail-per-file, not per-record, because writes to different universe ids still target the same JSON. The pattern (previously inlined in `pipeline/issues.js`, `pipeline/series.js`, and `mediaCollections.js`) is now factored into `server/lib/fileWriteQueue.js` — all four services share one implementation, so a future change to the queue contract is a one-place fix.- **CoS agents with Open PR enabled now merge their PR + delete the branch after Copilot review goes clean.** Claude Code CLI/TUI agents drive their own `/do:pr` flow, which opens the PR and runs the Copilot review loop but exits without merging — leaving the PR open and the worktree branch leaking. The CoS completion sections (`buildCliCompletionSection`, `buildTuiCompletionSection`, and the inline TUI block in the full/api path) now append an explicit `gh pr merge "<PR_URL>" --squash --delete-branch` step plus a `gh pr view ... -q .state` MERGED-verification step. The merge is skipped when the review loop ended `timeout`/`error`/`guardrail`, mirroring the contract the review-loop follow-up agent already uses.- **CoS Workflow tab now renders cleanly on desktop and mobile.** The stage columns had only `min-w-[12rem]` with no max — long stage descriptions stretched each column past 300px and forced horizontal scroll even on wide monitors. Columns now use responsive flex sizing on `2xl+` (`2xl:flex-1 2xl:basis-0 2xl:min-w-[11rem] 2xl:max-w-[15rem]`) so descriptions wrap predictably without forcing fixed widths, and the whole pipeline stacks vertically below `2xl` (with arrows hidden) for phones, tablets, and standard-density laptops where 7 stages won't fit horizontally. Cards inside each stage flow into a 2-column grid on `sm`–`2xl` so single-column stages don't waste tablet width. (Follow-up after the initial PR's squash-merge mixed `lg:` children with a `2xl:` parent wrapper — Copilot review flagged the breakpoint mismatch.)- **Volume cover-concept generation no longer 500s on upgraded installs.** The per-season "generate volume cover concepts" LLM step was shipped with its prompt template but missing from `stage-config.json`, so existing installs hit `Stage pipeline-volume-cover-concepts not found`. Added the config entry and a migration that seeds both the template and the config on next launch — fresh installs were already fine.diff --git a/PLAN.md b/PLAN.mdindex ccbea63533..751e13edc7 100644--- a/PLAN.md+++ b/PLAN.md@@ -14,7 +14,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]- **Phase D follow-ups (deferred from the Phase D PR):**- [ ] **Extract `resolveProviderAndModel({providerId, model})` into `server/lib/promptRunner.js`.** The same 5-line `getProviderById/getActiveProvider/resolveEffectiveModel` chain now lives in `expandWorldTemplate` (`universeBuilderExpand.js`), the refine entrypoint (`universeBuilderRefine.js`), AND `promoteVariationToCanon` (`universeBuilderPromote.js`). Three identical copies — consolidate next time we touch any of them.- [ ] **Add `findBibleEntryByName(list, name)` to `server/lib/storyBible.js`.** The "match name OR aliases case-insensitively" pattern lives in `promoteVariationToCanon` (duplicate-collision check) and `foldRetiredCharactersBucket` (seen-set construction) in `universeBuilder.js`. Will land a third caller when the Phase C auto-sort classifier ships.- - [ ] **Serialize universe write-paths server-side (`updateUniverse` queue per universe id).** Phase D ships a page-level client gate (`promoting` ref) that prevents the user from triggering concurrent promotes against one universe, but the server-side write path is still vulnerable to multi-client / multi-instance concurrent writes that compute `nextCanon`/`nextVariations` from stale snapshots and clobber each other. Mirror the `issueWriteTail`-style per-record queue pattern in `server/services/pipeline/issues.js` so every `updateUniverse(id, patch)` serializes on `id`. Per CLAUDE.md "Async PATCH races on shared records — serialize writes server-side."+ - [x] ~~**Serialize universe write-paths server-side.**~~ **Shipped 2026-05-17** — added `queueUniverseWrite` (single file-level queue) in `server/services/universeBuilder.js`. All five mutating fns (`createUniverse`, `insertUniverseWithId`, `updateUniverse`, `deleteUniverse`, `recordRun`) now enqueue onto it. The previously-inlined queue pattern from `pipeline/issues.js`, `pipeline/series.js`, and `mediaCollections.js` was extracted to a shared `server/lib/fileWriteQueue.js` factory (`createFileWriteQueue()`) and all four services were migrated onto it — drops 36 lines of copy-paste and the next pattern-tweak is a one-place fix. The unqueued migration write inside `readState()` was also removed (race-prone vs. concurrent queued writers); the next queued mutator persists the migrated shape naturally. Per CLAUDE.md "a `Map<recordId, Promise>` is *not* enough — collapse the queue to a single tail per shared file": same JSON file ⇒ single tail, not per-id. 4 regression tests cover same-universe concurrent PATCHes, cross-universe concurrent PATCHes, queue-poison-recovery, and recordRun + updateUniverse mixed concurrency; 4 helper tests pin the factory contract.- [ ] **Client component tests for `CategoryEditor` promote wiring + `TrunkView` button visibility.** Assert promote button disabled when `!selectedId`, picker opens for `kind: 'other'` buckets, picker option click invokes `onPromote` with the correct `targetKind`. No client vitest infra wired for `UniverseBuilder.jsx` yet — add when the page's first spec lands.- **Phase C follow-ups (deferred from the Phase C PR):**- [ ] **Auto-sort with AI** — LLM-classify each `kind: 'other'` bucket into characters/settings/objects + suggest a meaningful name. New server route `POST /api/universe-builder/:id/auto-sort` that sends bucket keys + variation labels to the active LLM and applies the classification. Currently the Other-tab button is a stub that points users at re-running Generate From Idea (Phase B's expand emits kind tags). Land in a follow-up to keep the Phase C PR scoped.diff --git a/server/lib/fileWriteQueue.js b/server/lib/fileWriteQueue.jsnew file mode 100644index 0000000000..8f5df1cd2d--- /dev/null+++ b/server/lib/fileWriteQueue.js@@ -0,0 +1,45 @@+/**+ * File Write Queue — single-tail promise chain for serializing writes+ * against a shared JSON state file.+ *+ * Every PortOS service that owns a single JSON state file (issues, series,+ * mediaCollections, universeBuilder, …) needs the same guarantee: a+ * `readState → modify → writeState` cycle must not interleave with another+ * cycle on the same file, or one writer's pre-image read overwrites the+ * other's just-persisted record. CLAUDE.md: "Async PATCH races on shared+ * records — serialize writes server-side… collapse the queue to a single+ * tail per shared file."+ *+ * Usage:+ * import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+ * const queueWrite = createFileWriteQueue();+ * // inside each mutator:+ * return queueWrite(async () => {+ * const state = await readState();+ * // ... modify ...+ * await writeState(state);+ * return result;+ * });+ *+ * The queue is per-file (per service module), not per-record — two writes+ * to different ids in the same JSON still race. Create one queue per state+ * file at module scope.+ */+export function createFileWriteQueue() {+ let tail = Promise.resolve();+ return function queue(fn) {+ const next = tail.then(fn, fn); // run fn even when prev rejects+ // Silenced tail prevents a rejection from poisoning subsequent waiters.+ const silenced = next.catch(() => {});+ tail = silenced;+ // When this write settles AND nothing else has chained onto it (i.e. it's+ // still the current tail), reset the tail to a fresh resolved promise so+ // the settled promise (and its resolved payload) can be GC'd. If another+ // write has already enqueued, `tail` points at that newer silenced+ // promise — the equality check is false and we leave it alone.+ silenced.finally(() => {+ if (tail === silenced) tail = Promise.resolve();+ });+ return next; // callers see the real resolve/reject+ };+}diff --git a/server/lib/fileWriteQueue.test.js b/server/lib/fileWriteQueue.test.jsnew file mode 100644index 0000000000..4853039a78--- /dev/null+++ b/server/lib/fileWriteQueue.test.js@@ -0,0 +1,52 @@+import { describe, it, expect } from "vitest";+import { createFileWriteQueue } from "./fileWriteQueue.js";++// Defer one event-loop tick (setImmediate is a check-phase macrotask, not a+// microtask) so we can interleave with another awaiter.+const tick = () => new Promise((r) => setImmediate(r));++describe("createFileWriteQueue", () => {+ it("runs queued fns in submission order even when their work yields", async () => {+ const queue = createFileWriteQueue();+ const order = [];+ const a = queue(async () => { await tick(); order.push("a"); });+ const b = queue(async () => { order.push("b"); });+ const c = queue(async () => { await tick(); order.push("c"); });+ await Promise.all([a, b, c]);+ expect(order).toEqual(["a", "b", "c"]);+ });++ it("an earlier rejection does not poison later waiters AND order is preserved", async () => {+ const queue = createFileWriteQueue();+ const order = [];+ // Without `tail.then(fn, fn)` (running fn on the rejection path), a+ // rejected tail would skip the next call's fn — the second test below+ // would fail. The `tick()` ensures the order assertion fails for a+ // pass-through queue (where parallel fns would land in submission order+ // but the rejecting one would still log AFTER the fast resolver).+ const bad = queue(async () => { await tick(); order.push("bad"); throw new Error("nope"); });+ const good = queue(async () => { order.push("good"); return "ok"; });+ await expect(bad).rejects.toThrow("nope");+ await expect(good).resolves.toBe("ok");+ expect(order).toEqual(["bad", "good"]);+ });++ it("each call sees the resolved value of its own fn", async () => {+ const queue = createFileWriteQueue();+ const r1 = await queue(() => Promise.resolve(1));+ const r2 = await queue(() => Promise.resolve(2));+ expect(r1).toBe(1);+ expect(r2).toBe(2);+ });++ it("separate queues are independent", async () => {+ const qA = createFileWriteQueue();+ const qB = createFileWriteQueue();+ const order = [];+ // qA's work yields; qB's work should not wait for it.+ const aSlow = qA(async () => { await tick(); order.push("a-slow"); });+ const bFast = qB(async () => { order.push("b-fast"); });+ await Promise.all([aSlow, bFast]);+ expect(order).toEqual(["b-fast", "a-slow"]);+ });+});diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex d4c0301db0..ecc18da35d 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -15,13 +15,14 @@* `addItem` running alongside Universe Builder's completion-hook `addItem`,* or a `deleteUniverse` unlink racing with an in-flight cover completion —* each do a `listCollections → modify → atomicWrite(entire array)` round- * and the second write silently clobbers the first. Mirrors the- * `issueWriteTail` pattern in `server/services/pipeline/issues.js`.+ * and the second write silently clobbers the first. Built on+ * `createFileWriteQueue()` in `server/lib/fileWriteQueue.js`.*/import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { emitRecordUpdated } from './sharing/recordEvents.js';@@ -128,27 +129,11 @@ export async function getCollection(id) {return c;}-// File-level write tail. Every public mutator wraps its read-modify-write-// in `serializeFileWrite` so the read always sees the freshest persisted-// state and the write completes before the next task's read begins.-// `writeAll` is the only persistence call and must only be invoked from-// inside a serialized task.-let fileWriteTail = Promise.resolve();-const serializeFileWrite = (task) => {- const next = fileWriteTail.then(task, task);- // Silence the tail so a rejection doesn't poison subsequent waiters.- // Mirror the issueWriteTail / seriesWriteTail pattern: when this write- // is still the tail after it settles, reset to a fresh Promise.resolve()- // so the chain doesn't retain settled promises (and their resolved- // payloads) for the life of the process. If another write enqueues- // first, it becomes the tail and we drop our reference.- const silenced = next.catch(() => {});- fileWriteTail = silenced;- silenced.finally(() => {- if (fileWriteTail === silenced) fileWriteTail = Promise.resolve();- });- return next;-};+// Every public mutator wraps its read-modify-write in `serializeFileWrite`+// so the read always sees the freshest persisted state and the write+// completes before the next task's read begins. `writeAll` is the only+// persistence call and must only be invoked from inside a serialized task.+const serializeFileWrite = createFileWriteQueue();const writeAll = async (collections) => {await atomicWrite(statePath(), { collections });return collections;diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 6d1dfe2125..fec64c4432 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -21,6 +21,7 @@import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';import {LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE,CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,@@ -40,26 +41,9 @@ const statePath = () => join(PATHS.data, 'pipeline-issues.json');// File-level write lock: serializes concurrent updateIssue / updateStage calls// against the shared pipeline-issues.json state file so a blur-save PATCH can// never clobber an in-flight cover-render PATCH (and vice-versa, across any-// pair of issues — not just two writes to the same issue id). Each enqueue-// awaits the previous write to settle before reading state, so it always-// merges against the freshest persisted record. CLAUDE.md: "simple-// re-entrancy guards… are fine and expected."-let issueWriteTail = Promise.resolve();--function queueIssueWrite(_issueId, fn) {- const next = issueWriteTail.then(fn, fn); // run fn even when prev rejects- // Track the silenced tail so a rejection doesn't poison subsequent waiters,- // but only as long as this write is the tail — if another write enqueues- // after us, it becomes the tail and we drop our reference so the chain- // doesn't retain settled promises (and their resolved payloads) for the- // life of the process.- const silenced = next.catch(() => {});- issueWriteTail = silenced;- silenced.finally(() => {- if (issueWriteTail === silenced) issueWriteTail = Promise.resolve();- });- return next; // callers still see the real resolve/reject-}+// pair of issues — not just two writes to the same issue id). CLAUDE.md:+// "simple re-entrancy guards… are fine and expected."+const queueIssueWrite = createFileWriteQueue();export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';@@ -365,7 +349,7 @@ export function createIssue(input = {}) {if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));const title = trimTo(input.title, TITLE_MAX);if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));- return queueIssueWrite(null, async () => {+ return queueIssueWrite(async () => {const state = await readState();const next = sanitizeIssue({id: `iss-${randomUUID()}`,@@ -407,7 +391,7 @@ async function renumberInline(state, seriesId, fromSeasonId = null) {}export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {- return queueIssueWrite(null, async () => {+ return queueIssueWrite(async () => {const state = await readState();const changed = await renumberInline(state, seriesId, fromSeasonId);if (!changed) return { changed: false };@@ -432,7 +416,7 @@ export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {* `series:updated` event regardless of the issue count.*/export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null) {- return queueIssueWrite(null, async () => {+ return queueIssueWrite(async () => {const state = await readState();let reassigned = 0;const now = new Date().toISOString();@@ -474,7 +458,7 @@ export function insertIssueWithId(input = {}) {if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));const title = trimTo(input.title, TITLE_MAX);if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));- return queueIssueWrite(input.id, async () => {+ return queueIssueWrite(async () => {const state = await readState();if (state.issues.some((i) => i.id === input.id)) {throw makeErr(`Issue id already exists: ${input.id}`, ERR_DUPLICATE);@@ -491,7 +475,7 @@ export function insertIssueWithId(input = {}) {}export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {- return queueIssueWrite(id, async () => {+ return queueIssueWrite(async () => {const state = await readState();const idx = state.issues.findIndex((i) => i.id === id);if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);@@ -596,7 +580,7 @@ export function updateStage(issueId, stageId, patch = {}) {}export function deleteIssue(id) {- return queueIssueWrite(id, async () => {+ return queueIssueWrite(async () => {const state = await readState();const idx = state.issues.findIndex((i) => i.id === id);if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);@@ -629,7 +613,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {// rather than waiting in line for an error it already knows about.return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));}- return queueIssueWrite(issueId, async () => {+ return queueIssueWrite(async () => {const state = await readState();const idx = state.issues.findIndex((i) => i.id === issueId);if (idx < 0) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);diff --git a/server/services/pipeline/seasonCoverFilenameHook.js b/server/services/pipeline/seasonCoverFilenameHook.jsindex 32f5e5002d..164505efd0 100644--- a/server/services/pipeline/seasonCoverFilenameHook.js+++ b/server/services/pipeline/seasonCoverFilenameHook.js@@ -10,7 +10,7 @@* Season covers live on the series record, not on an issue stage — so we* write a small bespoke handler that routes through* `seriesSvc.updateSeasonOnSeries`, which serializes against the shared- * `pipeline-series.json` via `seriesWriteTail`.+ * `pipeline-series.json` via `queueSeriesWrite` (see `lib/fileWriteQueue.js`).** Idempotency: skips when the slot's recorded `jobId` no longer matches* (a re-render landed between enqueue and this completion event). Thediff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 7424ff35cd..83a69f8036 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -14,6 +14,7 @@import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';import { isStr, trimTo } from '../../lib/storyBible.js';import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';import { sanitizeVisualStyleRef } from '../../lib/visualStyles.js';@@ -24,25 +25,14 @@ import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js// (e.g. tests that swap it through a Proxy mock).const statePath = () => join(PATHS.data, 'pipeline-series.json');-// File-level write lock — same pattern as issueWriteTail in issues.js.-// Required because multiple write paths can race on the single shared+// File-level write lock. Required because multiple write paths can race on the single shared// pipeline-series.json file: PATCH /series/:id (bible edits), PATCH// /seasons/:seasonId (season metadata), the new volume cover-render route,// the season-cover filename hook landing, and the bible-extract merge.// All of those read-then-write the same JSON; without serialization a// later writer's `readState` can land on a pre-image snapshot and clobber// the earlier write. CLAUDE.md: "single tail per shared file."-let seriesWriteTail = Promise.resolve();--function queueSeriesWrite(fn) {- const next = seriesWriteTail.then(fn, fn); // run fn even when prev rejects- const silenced = next.catch(() => {});- seriesWriteTail = silenced;- silenced.finally(() => {- if (seriesWriteTail === silenced) seriesWriteTail = Promise.resolve();- });- return next;-}+const queueSeriesWrite = createFileWriteQueue();export const ERR_NOT_FOUND = 'PIPELINE_SERIES_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_SERIES_VALIDATION';diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 15fd13598e..b472821471 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -28,6 +28,7 @@import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';import {sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE,@@ -55,6 +56,11 @@ export const CURRENT_SCHEMA_VERSION = 4;// proxy-mock pattern series.js's tests already use.const statePath = () => join(PATHS.data, 'universe-builder.json');+// Serializes every mutating call (create / update / delete / recordRun)+// against the shared universe-builder.json so concurrent writes — even to+// different universe ids — can't read a stale snapshot and clobber a sibling.+const queueUniverseWrite = createFileWriteQueue();+export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_VALIDATION = 'VALIDATION_ERROR';export const ERR_DUPLICATE = 'DUPLICATE';@@ -657,19 +663,28 @@ const sanitizeRun = (raw) => {};};+// Once-per-process flag for the canon-backfill log — readState() runs in both+// the queue and from un-queued readers, and the in-memory migration is cheap+// to recompute every read, but the log line should fire once.+let canonBackfillLogged = false;+async function readState() {await ensureDir(PATHS.data);const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });const rawById = new Map(Array.isArray(raw.universes) ? raw.universes.filter((u) => u?.id).map((u) => [u.id, u]) : []);const universes = Array.isArray(raw.universes) ? raw.universes.map(sanitizeTemplate).filter(Boolean) : [];const runs = Array.isArray(raw.runs) ? raw.runs.map(sanitizeRun).filter(Boolean) : [];- // Persist on first backfill so subsequent reads skip the work and the user- // is free to rename or delete canon entries without the backfill re-adding- // them from their source variation.- const migrated = universes.filter((u) => (rawById.get(u.id)?.schemaVersion || 0) < CURRENT_SCHEMA_VERSION);- if (migrated.length > 0) {- console.log(`🌍 Universe Builder canon backfill — migrated ${migrated.length} universe(s) to schemaVersion=${CURRENT_SCHEMA_VERSION}`);- await writeState({ universes, runs });+ // The in-memory result is always at CURRENT_SCHEMA_VERSION (sanitizeTemplate+ // re-stamps it on every read). Don't persist the migration here — that write+ // would race against any concurrent queued mutator's writeState and could+ // overwrite a freshly-patched record with the pre-patch migration baseline.+ // The next queued mutator persists the migrated shape naturally.+ if (!canonBackfillLogged) {+ const migrated = universes.filter((u) => (rawById.get(u.id)?.schemaVersion || 0) < CURRENT_SCHEMA_VERSION);+ if (migrated.length > 0) {+ console.log(`🌍 Universe Builder canon backfill — migrated ${migrated.length} universe(s) in-memory to schemaVersion=${CURRENT_SCHEMA_VERSION}; persists on next write`);+ canonBackfillLogged = true;+ }}return { universes, runs };}@@ -694,42 +709,44 @@ export async function getUniverse(id) {export async function createUniverse(input = {}) {const name = trimTo(input.name, NAME_MAX_LENGTH);if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);- const state = await readState();- const now = new Date().toISOString();- const next = sanitizeTemplate({- id: randomUUID(),- name,- starterPrompt: input.starterPrompt || '',- stylePrompt: input.stylePrompt || '',- negativePrompt: input.negativePrompt || '',- logline: input.logline || '',- premise: input.premise || '',- styleNotes: input.styleNotes || '',- categories: input.categories || {},- compositeSheets: input.compositeSheets || [],- influences: input.influences || {},- locked: input.locked || {},- // Canon registries — let callers seed a universe at creation time- // (writers-room promote, share-bucket import). sanitizeTemplate runs- // each through sanitizeBibleList, so per-entry shape is enforced.- characters: input.characters || [],- settings: input.settings || [],- objects: input.objects || [],- // Stamp the current schema so backfillCanonFromCategories takes its- // hot-path skip on first read. Without this, the legacy categories→- // canon backfill fires on every brand-new universe and re-pollutes- // `characters/settings/objects` with every category variation —- // counter to Phase B's separation of canon (named entities) from- // categories (exploratory variations). New universes are always at- // CURRENT_SCHEMA_VERSION; the backfill exists only for legacy reads.- schemaVersion: CURRENT_SCHEMA_VERSION,- llm: input.llm || {},- createdAt: now,- updatedAt: now,+ return queueUniverseWrite(async () => {+ const state = await readState();+ const now = new Date().toISOString();+ const next = sanitizeTemplate({+ id: randomUUID(),+ name,+ starterPrompt: input.starterPrompt || '',+ stylePrompt: input.stylePrompt || '',+ negativePrompt: input.negativePrompt || '',+ logline: input.logline || '',+ premise: input.premise || '',+ styleNotes: input.styleNotes || '',+ categories: input.categories || {},+ compositeSheets: input.compositeSheets || [],+ influences: input.influences || {},+ locked: input.locked || {},+ // Canon registries — let callers seed a universe at creation time+ // (writers-room promote, share-bucket import). sanitizeTemplate runs+ // each through sanitizeBibleList, so per-entry shape is enforced.+ characters: input.characters || [],+ settings: input.settings || [],+ objects: input.objects || [],+ // Stamp the current schema so backfillCanonFromCategories takes its+ // hot-path skip on first read. Without this, the legacy categories→+ // canon backfill fires on every brand-new universe and re-pollutes+ // `characters/settings/objects` with every category variation —+ // counter to Phase B's separation of canon (named entities) from+ // categories (exploratory variations). New universes are always at+ // CURRENT_SCHEMA_VERSION; the backfill exists only for legacy reads.+ schemaVersion: CURRENT_SCHEMA_VERSION,+ llm: input.llm || {},+ createdAt: now,+ updatedAt: now,+ });+ state.universes.push(next);+ await writeState(state);+ return next;});- state.universes.push(next);- await writeState(state);- return next;}/**@@ -743,81 +760,92 @@ export async function insertUniverseWithId(input = {}) {}const name = trimTo(input.name, NAME_MAX_LENGTH);if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);- const state = await readState();- if (state.universes.some((u) => u.id === input.id)) {- throw makeErr(`Universe id already exists: ${input.id}`, ERR_DUPLICATE);- }- const next = sanitizeTemplate({ ...input, name });- if (!next) throw makeErr('Invalid universe payload', ERR_VALIDATION);- state.universes.push(next);- await writeState(state);- return next;+ return queueUniverseWrite(async () => {+ const state = await readState();+ if (state.universes.some((u) => u.id === input.id)) {+ throw makeErr(`Universe id already exists: ${input.id}`, ERR_DUPLICATE);+ }+ const next = sanitizeTemplate({ ...input, name });+ if (!next) throw makeErr('Invalid universe payload', ERR_VALIDATION);+ state.universes.push(next);+ await writeState(state);+ return next;+ });}export async function updateUniverse(id, patch = {}) {- const state = await readState();- const idx = state.universes.findIndex((w) => w.id === id);- if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);- const cur = state.universes[idx];-- // Merge `categories` per-key — a partial PATCH that only includes- // `landscapes` must NOT wipe characters/structures/etc. Whole categories- // not present in the patch are kept as-is from the current universe.- const mergedCategories = 'categories' in patch- ? { ...cur.categories, ...(patch.categories || {}) }- : cur.categories;-- // Merge `llm` field-by-field — sending only `{ provider }` shouldn't- // clear `model` and vice versa.- const mergedLlm = 'llm' in patch- ? { ...(cur.llm || {}), ...(patch.llm || {}) }- : cur.llm;-- // `locked` replaces wholesale when the patch sends it (so unticking a lock- // actually unlocks). Skipped when the patch omits it.- const mergedLocked = 'locked' in patch ? (patch.locked || {}) : (cur.locked || {});-- // `influences` also replaces wholesale (each list is the user's full- // intended state — partial merging would leave stale entries the user- // thought they removed).- const mergedInfluences = 'influences' in patch ? (patch.influences || {}) : (cur.influences || {});-- // Scalar fields: only apply what the patch actually carries, so a partial- // PATCH never clobbers a field the caller didn't send. `categories` + `llm`- // + `locked` are handled above (they need per-key merging or wholesale- // replacement, not the simple scalar copy).- const PATCHABLE_SCALARS = [- 'name', 'starterPrompt',- 'logline', 'premise', 'styleNotes', 'compositeSheets',- // Canon entity arrays — patched wholesale (the sanitizer reruns- // sanitizeBibleList so per-entry shape is enforced on every save).- 'characters', 'settings', 'objects',- // Share-bucket origin metadata (importer sets it; user clears via wholesale null).- 'origin',- ];- const scalarPatch = Object.fromEntries(- PATCHABLE_SCALARS.filter((k) => k in patch).map((k) => [k, patch[k]]),- );-- const merged = sanitizeTemplate({- ...cur,- ...scalarPatch,- // sanitizeTemplate runs the v2 → v3 prose-prompt merge — see its- // `mergeLegacyPromptsIntoInfluences` call.- ...(patch.stylePrompt !== undefined ? { stylePrompt: patch.stylePrompt } : {}),- ...(patch.negativePrompt !== undefined ? { negativePrompt: patch.negativePrompt } : {}),- categories: mergedCategories,- influences: mergedInfluences,- locked: mergedLocked,- llm: mergedLlm,- updatedAt: new Date().toISOString(),+ // The queued section covers only the universe-builder read/modify/write+ // cycle. The cross-file media-collection rename runs *after* the queue+ // releases so a slow/stuck collection write can't block unrelated universe+ // mutators (the universe row is already persisted by then).+ const { merged, nameChanged } = await queueUniverseWrite(async () => {+ const state = await readState();+ const idx = state.universes.findIndex((w) => w.id === id);+ if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.universes[idx];++ // Merge `categories` per-key — a partial PATCH that only includes+ // `landscapes` must NOT wipe characters/structures/etc. Whole categories+ // not present in the patch are kept as-is from the current universe.+ const mergedCategories = 'categories' in patch+ ? { ...cur.categories, ...(patch.categories || {}) }+ : cur.categories;++ // Merge `llm` field-by-field — sending only `{ provider }` shouldn't+ // clear `model` and vice versa.+ const mergedLlm = 'llm' in patch+ ? { ...(cur.llm || {}), ...(patch.llm || {}) }+ : cur.llm;++ // `locked` replaces wholesale when the patch sends it (so unticking a lock+ // actually unlocks). Skipped when the patch omits it.+ const mergedLocked = 'locked' in patch ? (patch.locked || {}) : (cur.locked || {});++ // `influences` also replaces wholesale (each list is the user's full+ // intended state — partial merging would leave stale entries the user+ // thought they removed).+ const mergedInfluences = 'influences' in patch ? (patch.influences || {}) : (cur.influences || {});++ // Scalar fields: only apply what the patch actually carries, so a partial+ // PATCH never clobbers a field the caller didn't send. `categories` + `llm`+ // + `locked` are handled above (they need per-key merging or wholesale+ // replacement, not the simple scalar copy).+ const PATCHABLE_SCALARS = [+ 'name', 'starterPrompt',+ 'logline', 'premise', 'styleNotes', 'compositeSheets',+ // Canon entity arrays — patched wholesale (the sanitizer reruns+ // sanitizeBibleList so per-entry shape is enforced on every save).+ 'characters', 'settings', 'objects',+ // Share-bucket origin metadata (importer sets it; user clears via wholesale null).+ 'origin',+ ];+ const scalarPatch = Object.fromEntries(+ PATCHABLE_SCALARS.filter((k) => k in patch).map((k) => [k, patch[k]]),+ );++ const mergedRecord = sanitizeTemplate({+ ...cur,+ ...scalarPatch,+ // sanitizeTemplate runs the v2 → v3 prose-prompt merge — see its+ // `mergeLegacyPromptsIntoInfluences` call.+ ...(patch.stylePrompt !== undefined ? { stylePrompt: patch.stylePrompt } : {}),+ ...(patch.negativePrompt !== undefined ? { negativePrompt: patch.negativePrompt } : {}),+ categories: mergedCategories,+ influences: mergedInfluences,+ locked: mergedLocked,+ llm: mergedLlm,+ updatedAt: new Date().toISOString(),+ });+ if (!mergedRecord) throw makeErr('Invalid universe payload', ERR_VALIDATION);+ state.universes[idx] = mergedRecord;+ await writeState(state);+ return { merged: mergedRecord, nameChanged: mergedRecord.name !== cur.name };});- if (!merged) throw makeErr('Invalid universe payload', ERR_VALIDATION);- state.universes[idx] = merged;- await writeState(state);// Cascade rename onto the linked media collection — log but don't fail// the save: a stale collection name is recoverable, a failed save isn't.- if (merged.name !== cur.name) {+ // Runs OUTSIDE the queue so the media-collections write tail can't stall+ // subsequent universe mutators.+ if (nameChanged) {await renameCollectionForUniverse(merged.id, merged.name).catch((err) => {console.error(`❌ universe-collection rename cascade failed for ${merged.id}: ${err?.message || err}`);});@@ -827,18 +855,23 @@ export async function updateUniverse(id, patch = {}) {}export async function deleteUniverse(id) {- const state = await readState();- const before = state.universes.length;- state.universes = state.universes.filter((w) => w.id !== id);- if (state.universes.length === before) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);- // Drop runs referencing the deleted universe — they're useless without it.- state.runs = state.runs.filter((r) => r.universeId !== id);- await writeState(state);+ // Queue covers only the universe-builder write; cross-file unlink runs+ // after the queue releases so a slow media-collections write can't block+ // subsequent universe mutators.+ await queueUniverseWrite(async () => {+ const state = await readState();+ const before = state.universes.length;+ state.universes = state.universes.filter((w) => w.id !== id);+ if (state.universes.length === before) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);+ // Drop runs referencing the deleted universe — they're useless without it.+ state.runs = state.runs.filter((r) => r.universeId !== id);+ await writeState(state);+ });// Release the rename-lock on any linked media collections — without this,// the orphan collection's `universeId` stays stamped and the lock in// updateCollection blocks renames forever even though the universe is gone.// Best-effort: a failure here mustn't fail the delete (the universe is- // already gone from state).+ // already gone from state). Runs OUTSIDE the universe-builder queue.await unlinkCollectionsForUniverse(id).catch((err) => {console.error(`❌ unlink media collections for deleted universe ${id} failed: ${err?.message || err}`);});@@ -849,12 +882,14 @@ export async function deleteUniverse(id) {export async function recordRun(run) {const sanitized = sanitizeRun(run);if (!sanitized) throw makeErr('Invalid run payload', ERR_VALIDATION);- const state = await readState();- state.runs.push(sanitized);- // Keep last 200 runs to bound state growth.- if (state.runs.length > 200) state.runs = state.runs.slice(-200);- await writeState(state);- return sanitized;+ return queueUniverseWrite(async () => {+ const state = await readState();+ state.runs.push(sanitized);+ // Keep last 200 runs to bound state growth.+ if (state.runs.length > 200) state.runs = state.runs.slice(-200);+ await writeState(state);+ return sanitized;+ });}export async function listRuns(universeId = null) {diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex c4e1b49464..3da3178d59 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -1128,4 +1128,80 @@ describe("universeBuilder service", () => {.rejects.toMatchObject({ code: svc.ERR_VALIDATION });});});++ // Regression for "Async PATCH races on shared records — serialize writes+ // server-side" (CLAUDE.md). Each updateUniverse() now goes through a+ // file-level write tail so a stale snapshot can't clobber a sibling write.+ describe("write serialization", () => {+ it("concurrent updates to the same universe preserve every field", async () => {+ const u = await svc.createUniverse({ name: "Race" });+ // Five concurrent PATCHes, each touching a different scalar field.+ // Without the queue, every call reads the same pre-PATCH snapshot and+ // the last writeState wins — only one field would survive.+ await Promise.all([+ svc.updateUniverse(u.id, { logline: "L1" }),+ svc.updateUniverse(u.id, { premise: "P1" }),+ svc.updateUniverse(u.id, { styleNotes: "S1" }),+ svc.updateUniverse(u.id, { starterPrompt: "SP1" }),+ svc.updateUniverse(u.id, { name: "N1" }),+ ]);+ const final = await svc.getUniverse(u.id);+ expect(final.logline).toBe("L1");+ expect(final.premise).toBe("P1");+ expect(final.styleNotes).toBe("S1");+ expect(final.starterPrompt).toBe("SP1");+ expect(final.name).toBe("N1");+ });++ it("concurrent updates to DIFFERENT universes preserve every field", async () => {+ // Per CLAUDE.md: a Map<id, Promise> is NOT enough — both universes+ // share the same JSON file, so writes to different ids can still race.+ // The single file-level tail covers this.+ const a = await svc.createUniverse({ name: "A" });+ const b = await svc.createUniverse({ name: "B" });+ await Promise.all([+ svc.updateUniverse(a.id, { logline: "A-line", premise: "A-premise" }),+ svc.updateUniverse(b.id, { logline: "B-line", premise: "B-premise" }),+ ]);+ const fa = await svc.getUniverse(a.id);+ const fb = await svc.getUniverse(b.id);+ expect(fa.logline).toBe("A-line");+ expect(fa.premise).toBe("A-premise");+ expect(fb.logline).toBe("B-line");+ expect(fb.premise).toBe("B-premise");+ });++ it("a rejecting write does not poison the queue", async () => {+ // Force the rejection from INSIDE the queue (after the writeState would+ // run) so this actually pins poison-recovery rather than passing through+ // a fail-before-queue path. The first call's ERR_NOT_FOUND fires inside+ // the queued closure (the universe-id lookup happens after `readState`).+ const u = await svc.createUniverse({ name: "PoisonTest" });+ const results = await Promise.allSettled([+ svc.updateUniverse("nonexistent-universe", { logline: "X" }),+ svc.updateUniverse(u.id, { logline: "ok" }),+ ]);+ expect(results[0].status).toBe("rejected");+ expect(results[0].reason?.code).toBe(svc.ERR_NOT_FOUND);+ expect(results[1].status).toBe("fulfilled");+ const final = await svc.getUniverse(u.id);+ expect(final.logline).toBe("ok");+ });++ it("concurrent recordRun + updateUniverse don't clobber each other", async () => {+ const u = await svc.createUniverse({ name: "RunRace" });+ await Promise.all([+ svc.updateUniverse(u.id, { logline: "L" }),+ svc.recordRun({ id: "run-1", universeId: u.id, promptCount: 5 }),+ svc.updateUniverse(u.id, { premise: "P" }),+ svc.recordRun({ id: "run-2", universeId: u.id, promptCount: 7 }),+ ]);+ const final = await svc.getUniverse(u.id);+ const runs = await svc.listRuns(u.id);+ expect(final.logline).toBe("L");+ expect(final.premise).toBe("P");+ expect(runs).toHaveLength(2);+ expect(runs.map((r) => r.id).sort()).toEqual(["run-1", "run-2"]);+ });+ });});