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([universe-builder-llm-action-read-modify-write-inside-queue, universe-builder-flush-draft-before-llm-actions]): close Phase C concurrency follow-ups

[._.]/ Adam Eivy01892aaceaf9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 40ddb6579e..6b04435a44 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -35,3 +35,5 @@
- **`updateUniverse(id, patch, options)`** API client now passes options through to the underlying `request()` helper, enabling silent error mode.
- **`resolveProviderAndModel({providerId, model})`** added to `server/lib/promptRunner.js`. Collapses the 4 inlined `getProviderById/getActiveProvider/resolveEffectiveModel` chains in `universeBuilderExpand.js` (×2), `universeBuilderRefine.js`, and `universeBuilderPromote.js` onto one helper. The next caller is a one-import addition; the previous pattern was already drifting in error-handling specifics.
- **`findBibleEntryByName(list, name)`** added to `server/lib/storyBible.js` for the "match name OR aliases case-insensitively" predicate. Replaces the inlined `.find(...)` in `universeBuilderPromote.js`'s duplicate-collision check. (`foldRetiredCharactersBucket` keeps its O(1) `Set` index over normalized names+aliases — a per-iteration live-array lookup would be O(n*m) when folding a large retired bucket against a large canon.)
+- **`updateUniverse(id, mutator)` callback overload** (`server/services/universeBuilder.js`). `updateUniverse` now also accepts an async `mutator(latest) => patch | null` callback that runs INSIDE `queueUniverseWrite` against the freshest persisted record. `autoSortOtherBuckets` and `promoteVariationToCanon` route their read-modify-write through it — closes the narrow race where a concurrent edit landing between the LLM call and the persist could be silently dropped. Promote's variation removal now re-locates by label inside the queue (the pre-LLM `sourceIdx` is stale by write time) and re-checks the duplicate-name 409 against the latest canon, surfacing `UNIVERSE_PROMOTE_CATEGORY_GONE` / `UNIVERSE_PROMOTE_VARIATION_GONE` when the bucket/variation disappears mid-flight. Duplicate-collision detection lives in a single `findCanonCollision(canon, label, targetKind, secondarySlug?)` helper used by both the pre-LLM short-circuit and the in-queue re-check. +6 server tests pinning the overload contract (happy path, null short-circuit, throw propagation, non-object validation, array rejection, queue-ordering against a parallel literal-patch write).
+- **Universe Builder — flush dirty draft before LLM-driven mutators.** `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` previously operated against the server-persisted universe; if the user had unsaved local edits when they clicked, the server's stale copy got merged back into the draft and silently discarded the pending edits. The page now tracks a `savedDraftSnapshotRef` baseline (via a `markDraftSaved` helper, computed by `draftSnapshotForDirty`) and each LLM handler awaits `handleSave()` first when the draft is dirty, aborting on save failure. `useUniverseAction` gained an optional `preflight` callback that runs AFTER the ref/savedId guards so double-clicks short-circuit before flushing. +4 client tests covering the preflight contract (returns-false abort, throw-as-false, returns-true continue, post-ref-guard ordering).
diff --git a/DONE.md b/DONE.md
index 2281b8b14e..6ddc690ff8 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-17
+- **[universe-builder-redesign-trunks-sub-buckets] Universe Builder redesign — trunks + sub-buckets layout (Phases A–D + Phase C follow-ups).** Multi-phase rewrite landing across 2026-05-15 → 2026-05-17. Phase A added a `kind: 'characters'|'settings'|'objects'|'other'` field to every category bucket + a migration to backfill the built-in defaults; Phase B taught `buildExpansionPrompt()` + `isExpansionShape()` to emit and accept rich canon arrays alongside categories, with client-side `handleExpand` merging canon entries into `universe.{characters,settings,objects}` (dedupe by name, respect locks); Phase C rewrote the page as a tabbed-trunk layout (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state, a unified `EntryCard` rendering both canon entries and category variations, and per-trunk / per-bucket / all-canon batch-render targeting; Phase D shipped `POST /:id/promote-variation` to LLM-expand a variation into a full canon entry (atomic canon append + variation removal in one `updateUniverse` patch, duplicate-name 409 before the LLM call, trunk picker for `kind: 'other'` buckets). Phase C follow-ups closed today: (1) `updateUniverse(id, mutator)` now accepts an async `mutator(latest) => patch` callback that runs INSIDE `queueUniverseWrite` — `autoSortOtherBuckets` and `promoteVariationToCanon` route their read-modify-write through this so a slow LLM call can't admit a concurrent edit between read and persist; promote's variation removal also re-locates by label inside the queue rather than relying on the stale pre-LLM index, and the duplicate-name 409 is re-checked against the latest canon (returns `UNIVERSE_PROMOTE_CATEGORY_GONE` / `UNIVERSE_PROMOTE_VARIATION_GONE` when the bucket/variation disappears mid-flight); (2) `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` now flush a dirty draft via `handleSave()` before kicking off — `UniverseBuilder.jsx` tracks a `savedDraftSnapshotRef` baseline (compared via `draftSnapshotForDirty`) that updates on universe-load, manual save, expand auto-save, refine auto-save, generate auto-save, and after each LLM mutator's `onFreshResult` merge. `useUniverseAction` gained a `preflight` option that runs AFTER the ref/savedId guard so double-clicks short-circuit before flushing. 5 new server tests (`updateUniverse` mutator overload — happy path, null-skip, throw-propagation, non-object validation, queue-ordering against a parallel literal-patch write) + 4 new client tests (`useUniverseAction` preflight — returns-false abort, throw-as-false, returns-true continue, post-ref-guard ordering).
- **[extract-useuniverseaction-hook] Extract `useUniverseAction` hook from `UniverseBuilder.jsx`.** New `client/src/hooks/useUniverseAction.js` consolidates the scaffolding shared by `handlePromoteVariation` + `handleAutoSort`: `selectedId` guard, per-action ref re-entrancy, `capturedId` snapshot, loading-toast lifecycle (`silent: true` + `.catch` → dismiss + error), mountedRef-gated busy reset, always-update `setWorlds`, and the `mountedRef.current && capturedId === selectedId` stale-write guard. Each caller now passes only what varies — its `ref`/`setBusy`/`loadingMessage`/`errorPrefix`/`notSavedMessage`, the API call (receives `capturedId`), and an `onFreshResult(result)` callback that does the selective `setDraft` and returns the success-toast string. `handleGenerateInCategory` is intentionally NOT a consumer (the PLAN line's "to a lesser extent" — eager local merge first + best-effort save is a different shape; forcing it through would warp it); the hook header documents this. 9 new vitest cases in `useUniverseAction.test.jsx` (selectedId guard, re-entrancy, happy path, stale-write, action-rejects, no-loading-toast variant, falsy-universe result, suppressed-toast onFreshResult, unmount mid-flight). PLAN.md description gated this on "extract when a 4th handler lands"; promoted now with 3 — the hook itself is small and the scaffold is the most-bug-prone piece of these handlers.
- **[extract-builduniversestylecontext-helper] Extract `buildUniverseStyleContext(universe, options)` helper.** New helper in `server/services/universeBuilder.js` (next to `joinInfluenceList`) renders the shared "Universe context" prompt block (LOGLINE / optional PREMISE / STYLE NOTES / optional EMBRACE INFLUENCES). Three call sites collapsed: `buildAutoSortPrompt` (`universeBuilderAutoSort.js`, `escape: true`), `buildPromotePrompt` (`universeBuilderPromote.js`, default opts + headerSuffix), and `buildCategoryGeneratePrompt` (`universeBuilderExpand.js`, `includePremise: true` + `includeEmbrace: false` since it has its own influences section). Toggles cover the actual variance: `includePremise`, `includeEmbrace`, `escape` (newline/control-char stripping for defense-in-depth), `headerSuffix` (per-call header framing). 9 new unit tests in `universeBuilder.test.js` assert byte-exact outputs for each call shape. Pipeline call sites at `visualStages.js` and `seriesTitleLogo.js` were inspected but are out of scope — they only use `joinInfluenceList` for render-style composition and template variables, not the LOGLINE/STYLE NOTES/EMBRACE block. `buildExpansionPrompt`'s "Current universe state" block also stays separate — its `[LOCKED]` flags + `LOCKABLE_FIELD_LABELS` make it too distinct to fold without compromising the helper.
- **[extract-descriptorforcanonentry-kind-entry-into] Extract `descriptorForCanonEntry(kind, entry)` into `server/lib/canonPrompt.js` (mirror in client).** New `server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` mirror is the single source of truth for per-kind canon descriptor fields. Exports `shortCanonDescriptorFragments` (UI summary scope: physicalDescription || description for chars; description + Palette + recurringDetails for settings; description || significance for objects), `richCanonDescriptorFragments` (adds role, era, weather, significance-as-additive — the render-prompt scope), `descriptorForCanonEntry` (flattened short string matching legacy `KINDS[].descFor`), and `hasCanonDescriptorContent` (rich-field union for "is there anything to render?" gates). Migrated four call sites: `synthesizeCanonPrompt` (`server/services/universeBuilder.js`), `KINDS[].descFor` (`client/src/components/universe/UniverseCanonSection.jsx`), `canonEntryHasContent` (`client/src/pages/UniverseBuilder.jsx`), and `settingFrags` in `server/lib/scenePrompt.js` + client mirror. Tests: 29 new in `server/lib/canonPrompt.test.js`. Minor cosmetic uniformity in canon render prompts: lowercase `palette:`/`era:`/`weather:`/`significance:` prefixes are now capitalized (`Palette:` etc.) to match the UI descriptor format — case-only diff, no functional impact on diffusion models.
diff --git a/PLAN.md b/PLAN.md
index 7537d2b14b..d9593e2a99 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,14 +6,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
## Next Up
-1. **Universe Builder redesign — trunks + sub-buckets layout.** Replace the vertical-stack layout with a tabbed-trunk layout (`Bible / Cast / Places / Objects / Composites / Render`). Unify custom categories as sub-buckets under one of the 3 canon trunks via a new `kind: 'characters'|'settings'|'objects'` field on each category. Card grids with thumbnails replace the per-category accordion. Multi-phase (each phase is its own PR):
- - **Phase A — Data model + migration.** Add `kind: 'characters'|'settings'|'objects'|'other'` field to category sanitizer (`server/services/universeBuilder.js#sanitizeCategories`) and Zod (`server/routes/universeBuilder.js#categoryShape`); default to `'other'` when missing/invalid. Sub-bucket keys remain **globally unique** (no per-trunk namespacing). Migration `scripts/migrations/NNN-categorize-universe-buckets.js` assigns built-in defaults: `landscapes/environments/structures → settings`, `vehicles → objects`. The default `characters` category is retired; its variations backfill into `universe.characters[]` (reuse `backfillCanonFromCategories` logic). All other existing custom categories get `kind: 'other'`; Phase C surfaces them under an **Other** tab with an **Auto-sort** button that LLM-classifies each bucket into the right trunk + a meaningful name.
- - **Phase B — Expand contract enrichment.** Teach `buildExpansionPrompt()` (`server/services/universeBuilderExpand.js`) to return rich canon arrays (`characters[]`/`settings[]`/`objects[]` with `physicalDescription`/`palette`/`recurringDetails`/`wardrobe`) alongside the existing `categories` (now kind-tagged) + `compositeSheets`. Update `isExpansionShape()` predicate. Client `handleExpand` in `UniverseBuilder.jsx` merges canon entries into the canon arrays parallel to the category merge (dedupe by name, respect per-entry locks). Categories the LLM emits include a `kind` so they land under the right trunk.
- - **Phase C — Layout rewrite.** Tabbed top-level (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state (`?tab=cast&bucket=heroes` per CLAUDE.md linkable-routes convention) — Bible is its own tab (not a sticky header). Per-trunk view = sub-bucket chip filter row + responsive card grid. Unify `CanonCard` + a new card for category variations into a single `EntryCard` component (renders thumbnail from `primaryImageRef` or most recent render). **Canon entries are first-class batch-render targets** alongside category variations and composite sheets: per-bucket actions are "Generate N more" + "Bulk-render this bucket"; per-trunk action is "Bulk-render all Cast/Places/Objects" (includes BOTH canon entries AND every variation in every sub-bucket under that trunk); the Batch Render tab itself offers per-trunk, per-bucket, and "All canon" selectors plus the existing composite-sheets mode. Composite reference images stay intact as their own render mode (no regression). Server-side: extend `compilePrompts` to accept canon entries as render sources (synthesize a prompt from `name + physicalDescription/palette/description`, layered with the universe style preset the same way variations are today). The **Other** tab only appears when un-kinded buckets exist, and shows the **Auto-sort with AI** action. Mobile: tabs collapse to a select dropdown.
- - **Phase D — Polish & promotion.** ~~"Promote variation to canon" action~~ shipped: `POST /api/universe-builder/:id/promote-variation` LLM-expands a `{label, prompt}` variation into a full canon entry (per-kind `physicalDescription` / `slugline`+`palette` / `description`+`significance`) and atomically writes the canon append + variation removal in one `updateUniverse` patch. CategoryEditor renders a promote button per row; Other-tab buckets open a trunk picker (since `kind: 'other'` can't be auto-resolved). Duplicate-name collisions short-circuit with a 409 before the LLM call. Deferred: client component tests; standalone design doc (not warranted — CLAUDE.md notes + this PR's prose cover the contract).
- - **Phase C follow-ups (deferred from the Phase C PR):**
- - [ ] [universe-builder-llm-action-read-modify-write-inside-queue] **Move LLM-action read-modify-write inside `queueUniverseWrite`.** `autoSortOtherBuckets` (and `promoteVariationToCanon`) currently read the universe state, run a long LLM call, then write — the gap between the LLM call and `updateUniverse` admits a narrow race where another tab can edit the same bucket. The service-level refetch right before write narrows the window to ~ms but doesn't eliminate it (concurrent writes between refetch and `updateUniverse`'s own queued readState can still drop a variation). Real fix: extend `updateUniverse` to accept a `mutator(latest) => patch` callback so the read-modify-write runs inside the file-level queue. Cross-cutting (touches every LLM-driven mutator).
- - [ ] [universe-builder-flush-draft-before-llm-actions] **Flush dirty draft before triggering LLM-driven mutators.** `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` operate against the server-persisted universe; if the user has unsaved local edits to a bucket and clicks one of these, the server's stale copy comes back and gets merged into the draft, silently discarding the local edits. Either auto-save on click (and wait for confirmation) or gate the buttons on `!isDirty`. Decide which after looking at what `isDirty` means in this page (`draftRef` vs `worlds` snapshot).
+_Nothing currently parked — pick the next item from the Backlog._
## Backlog
@@ -34,9 +27,9 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
### Universe-as-Canon — Phase 2 + extensions
- [ ] [canoncard-from-series-name-full-provenance-label] **CanonCard "from series: <name>" full provenance label.** Card currently shows a "from series" chip with the series id in the tooltip. Plumb a `seriesNameMap` (or `sourceSeriesName` per entry) so the chip can render the actual series name. Needs the parent (`UniverseCanonSection` / `NounsStage`) to pass a `{ [seriesId]: name }` lookup.
-- [→] **Drop the default `characters` category.** Folded into Next Up #1 Phase A.
-- [→] **Universe expand LLM contract enrichment.** Folded into Next Up #1 Phase B.
-- [→] **arcPlanner prompt context — include canon characters/places/objects.** Folded into Next Up #1 Phase B (Phase B PR shipped `renderCanonForPrompt(world)` + `worldCanonText` + migration 019 for all four arc/volume templates: `pipeline-arc-overview`, `pipeline-arc-verify`, `pipeline-arc-resolve`, `pipeline-volume-verify`). Follow-up: sweep `grep -rn "world\.categories" server/services/pipeline server/services/universeBuilder*.js` for other prompt builders that read categories but not canon.
+- [x] ~~**Drop the default `characters` category.**~~ Shipped via the Universe Builder redesign Phase A migration; default `characters` bucket retired, variations backfilled into `universe.characters[]`.
+- [x] ~~**Universe expand LLM contract enrichment.**~~ Shipped via the Universe Builder redesign Phase B — expand contract now returns rich canon arrays alongside categories.
+- [x] ~~**arcPlanner prompt context — include canon characters/places/objects.**~~ Shipped via the Universe Builder redesign Phase B (`renderCanonForPrompt(world)` + `worldCanonText` + migration 019 for `pipeline-arc-overview`, `pipeline-arc-verify`, `pipeline-arc-resolve`, `pipeline-volume-verify`). Follow-up still open: sweep `grep -rn "world\.categories" server/services/pipeline server/services/universeBuilder*.js` for other prompt builders that read categories but not canon.
- [ ] [bible-kind-setting-rename-to-place] **Bible `SETTING` kind rename to `PLACE`.** Rename the bible-domain "setting" entity to "place" everywhere it's an identifier (NOT app settings — `data/settings.json` and `/api/settings` are unrelated and stay). Migration 018 (2026-05-17, PR #265) already renamed the `writers-room-settings` stage-config key + prompt template file; this is the broader enum/field/route/data-shape rename it explicitly deferred.
@@ -59,7 +52,8 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
**Non-goals / out of scope:** `data/settings.json`, the Settings page, the `/api/settings` routes, app-level user-prefs — all stay as "settings".
- **Why now:** with the 3-canon-trunks architecture (Cast / Places / Objects) fully shipped (Next Up #1), the user-facing terminology is "Places" everywhere except inside the bible code. This finishes that alignment so a future contributor doesn't have to mentally translate `setting ↔ place`.
+ **Why now:** with the 3-canon-trunks architecture (Cast / Places / Objects) fully shipped (see the Universe Builder redesign in DONE.md, 2026-05-17), the user-facing terminology is "Places" everywhere except inside the bible code. This finishes that alignment so a future contributor doesn't have to mentally translate `setting ↔ place`.
+
- [ ] [use-rendered-reference-images-as-i2i-anchors-in] **Use rendered reference images as i2i anchors in downstream comic-page renders for models that support it.** SDXL/Flux pipelines anchor every panel render on the per-character rendered ref.
### Pipeline continuity / approval
@@ -144,7 +138,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- [ ] [med-sharing-server-services-sharing-version-js] **[MED][SHARING]** `server/services/sharing/version.js` — `SHARING_SCHEMA_VERSION` not bumped despite series-schema canon-field removal. Cross-peer share-bucket import from a pre-B.4 install silently loses series-side canon. Either bump the version (force refusal) or mirror migration logic in the importer for legacy canon fields.
- [ ] [med-ai-dispatch-server-services-aidetect-js-242] **[MED][AI-DISPATCH]** `server/services/aiDetect.js:242-250` — still has legacy `if (provider.type === 'cli') ... else if (api) ... else 'Unknown provider type'`. TUI providers fail on Settings → Detect App. Migrate to `runPromptThroughProvider`.
- [ ] [med-ai-dispatch-server-services-digital-twin] **[MED][AI-DISPATCH]** `server/services/digital-twin-helpers.js:56-130` — `callProviderAI` still has ad-hoc CLI/API split with TUI falling into the CLI branch (will hang or render banner into pipe). Migrate to `runPromptThroughProvider`.
-- [ ] [med-ai-dispatch-server-lib-tuipromptrunner-js-198] **[MED][AI-DISPATCH]** `server/lib/tuiPromptRunner.js:198-200` — `OUTPUT_BUFFER_CAP = 1MB` silently truncates the *head* of TUI responses >1.25MB mid-token. Persists to disk AND returns truncated. Either stream incrementally to `output.txt` (like agentTuiSpawning does) or raise the cap + log a warning.
+- [ ] [med-ai-dispatch-server-lib-tuipromptrunner-js-198] **[MED][AI-DISPATCH]** `server/lib/tuiPromptRunner.js:198-200` — `OUTPUT_BUFFER_CAP = 1MB` silently truncates the _head_ of TUI responses >1.25MB mid-token. Persists to disk AND returns truncated. Either stream incrementally to `output.txt` (like agentTuiSpawning does) or raise the cap + log a warning.
- [ ] [med-tests-no-tests-for-server-lib-ansistrip-js] **[MED][TESTS]** No tests for `server/lib/ansiStrip.js` (streaming escape-split-across-chunks logic) or `server/lib/tuiHandshake.js` (paste timing constants both production paths depend on). Add coverage for: escape split across two chunks, bare `\x1B` at chunk end, OSC sequences, unterminated bytes past the 4096-byte window.
- [ ] [med-tests-no-direct-tests-for-executetuirun-pty] **[MED][TESTS]** No direct tests for `executeTuiRun` PTY mechanics — idle-complete, hard-timeout, missing-binary early-fail, `emitRunStarted` shape, CLAUDECODE env stripping. The new `tuiPromptRunner.test.js` only covers `cleanTuiResponse`.
- [ ] [med-importer-server-routes-importer-test-js-no] **[MED][IMPORTER]** `server/routes/importer.test.js` — no test pins `ERR_PARTIAL_COMMIT_ISSUES → 207` status mapping. Future refactor that drops the entry from `SERVICE_ERROR_STATUS` would 500 on partial commits and trigger pager alerts (the in-code comment's stated regression).
@@ -154,7 +148,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- [ ] [low-ai-dispatch-server-services-loops-js-181-fire] **[LOW][AI-DISPATCH]** `server/services/loops.js:181` — fire-and-forget `.then(...).catch(err => ...)` chain causes a throw in `onComplete({success:true})` to be misclassified as iteration-failed and emit `iteration:error`. Split into separate `.then` or wrap onComplete with its own catch.
- [ ] [low-canon-server-services-pipeline-textstages-js] **[LOW][CANON]** `server/services/pipeline/textStages.js:156` — dead-code fallback `|| series.characters` (always `undefined` post-B.4). Drop the middle clause.
- [ ] [low-canon-server-services-pipeline] **[LOW][CANON]** `server/services/pipeline/migrateSeriesCanon.js:61` — `updateSeries({ universeId })` writes mid-loop with the universe still empty. Crash between line 61 and the universe patch leaves series stripped + universe empty. Build the universe patch first, then write both.
-- [ ] [low-importer-server-services-importer-js-444-446] **[LOW][IMPORTER]** `server/services/importer.js:444-446` — `arcSummary = arcContent.summary || arcContent.logline || \`${name} — ${type}\`` silently swallows a successful arc-extract that returned empty fields. Log a warning or surface `arcExtractFallback: true`.
+- [ ] [low-importer-server-services-importer-js-444-446] **[LOW][IMPORTER]** `server/services/importer.js:444-446` — `arcSummary = arcContent.summary || arcContent.logline || \`${name} — ${type}\``silently swallows a successful arc-extract that returned empty fields. Log a warning or surface`arcExtractFallback: true`.
- [ ] [low-sharing-server-services-mediaannotations-js] **[LOW][SHARING]** `server/services/mediaAnnotations.js:154` — peer `updatedAt` not clamped to `Math.min(now, sane.updatedAt)`; a peer with future-skewed clock dominates all merges.
- [ ] [low-sharing-server-services-mediaannotations-js-2] **[LOW][SHARING]** `server/services/mediaAnnotations.js:132-167` — `mergePeerAnnotations` accepts `peerInstanceId === 'unknown'`; the outgoing path guards but the import side doesn't. Add `if (!peerInstanceId || peerInstanceId === 'unknown') return ...`.
- [ ] [low-sharing-server-services-sharing] **[LOW][SHARING]** `server/services/sharing/annotationsSync.js:38-68` — empty-payload writes fan to every auto-merge bucket per local edit. Skip when both prior and current filtered payloads are empty.
diff --git a/client/src/hooks/useUniverseAction.js b/client/src/hooks/useUniverseAction.js
index 6c1fce47da..80b16137ed 100644
--- a/client/src/hooks/useUniverseAction.js
+++ b/client/src/hooks/useUniverseAction.js
@@ -14,6 +14,11 @@ import toast from '../components/ui/Toast';
// toasts only fire from this hook (per CLAUDE.md "Custom catch ⇒ silent").
// `onFreshResult(result, { capturedId })` runs only when the user is still
// on the same universe; return a string to use as the success toast.
+// `preflight()` runs AFTER the ref/savedId guards (so duplicate clicks short-
+// circuit before it fires) but BEFORE the loading toast + LLM action. Return
+// a falsy value to abort (the preflight is responsible for any failure toast).
+// Used to flush a dirty draft via handleSave() so the LLM action operates
+// against the user's latest local edits rather than a stale persisted copy.
export default function useUniverseAction({ selectedId, mountedRef, setWorlds }) {
return useCallback(async function runUniverseAction({
ref,
@@ -23,6 +28,7 @@ export default function useUniverseAction({ selectedId, mountedRef, setWorlds })
notSavedMessage = 'Save the universe first',
action,
onFreshResult,
+ preflight,
}) {
if (!selectedId) {
toast.error(notSavedMessage);
@@ -31,6 +37,16 @@ export default function useUniverseAction({ selectedId, mountedRef, setWorlds })
if (ref?.current) return null;
if (ref) ref.current = true;
setBusy?.(true);
+ if (typeof preflight === 'function') {
+ const ok = await preflight().catch(() => false);
+ if (!ok) {
+ if (mountedRef.current) {
+ if (ref) ref.current = false;
+ setBusy?.(false);
+ }
+ return null;
+ }
+ }
const capturedId = selectedId;
const toastId = loadingMessage ? toast.loading(loadingMessage) : null;
diff --git a/client/src/hooks/useUniverseAction.test.jsx b/client/src/hooks/useUniverseAction.test.jsx
index 3f9d953585..d612c3014f 100644
--- a/client/src/hooks/useUniverseAction.test.jsx
+++ b/client/src/hooks/useUniverseAction.test.jsx
@@ -140,6 +140,65 @@ describe('useUniverseAction', () => {
expect(toastMock.success).not.toHaveBeenCalled();
});
+ it('preflight returning false aborts before action, resets ref + busy', async () => {
+ const { run } = buildHook();
+ const ref = { current: false };
+ const setBusy = vi.fn();
+ const action = vi.fn();
+ const preflight = vi.fn(async () => false);
+ const out = await run({
+ ref, setBusy,
+ loadingMessage: 'go',
+ action,
+ preflight,
+ });
+ expect(out).toBeNull();
+ expect(preflight).toHaveBeenCalledTimes(1);
+ expect(action).not.toHaveBeenCalled();
+ expect(toastMock.loading).not.toHaveBeenCalled();
+ expect(ref.current).toBe(false);
+ expect(setBusy).toHaveBeenNthCalledWith(1, true);
+ expect(setBusy).toHaveBeenNthCalledWith(2, false);
+ });
+
+ it('preflight rejecting (throw) aborts the same as returning false', async () => {
+ const { run } = buildHook();
+ const ref = { current: false };
+ const action = vi.fn();
+ const preflight = vi.fn(async () => { throw new Error('save failed'); });
+ const out = await run({ ref, action, preflight });
+ expect(out).toBeNull();
+ expect(action).not.toHaveBeenCalled();
+ expect(ref.current).toBe(false);
+ });
+
+ it('preflight returning true allows the action to run', async () => {
+ const { run } = buildHook();
+ const ref = { current: false };
+ const action = vi.fn(async (id) => ({ universe: { id, name: 'after-flush' } }));
+ const preflight = vi.fn(async () => true);
+ const out = await run({
+ ref,
+ action,
+ preflight,
+ onFreshResult: () => 'ok',
+ });
+ expect(preflight).toHaveBeenCalledTimes(1);
+ expect(action).toHaveBeenCalledWith('u1');
+ expect(out).toEqual({ universe: { id: 'u1', name: 'after-flush' } });
+ });
+
+ it('preflight runs AFTER the ref guard so double-clicks short-circuit before flushing', async () => {
+ const { run } = buildHook();
+ const ref = { current: true };
+ const preflight = vi.fn(async () => true);
+ const action = vi.fn();
+ const out = await run({ ref, action, preflight });
+ expect(out).toBeNull();
+ expect(preflight).not.toHaveBeenCalled();
+ expect(action).not.toHaveBeenCalled();
+ });
+
it('unmount before action resolves: ref/busy NOT reset, but setWorlds still fires (cross-navigation list update)', async () => {
const setWorlds = vi.fn();
const { run, mountedRef } = buildHook({ setWorlds });
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 5f39cdb1ef..94d0e540b4 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -260,6 +260,22 @@ const emptyTemplate = () => ({
llm: { provider: null, model: null },
});
+// Stable serialization of the draft fields handleSave persists. Canon arrays
+// are excluded — they're owned by UniverseCanonSection/NounsStage's targeted
+// PATCHes, not this page's draft.
+const draftSnapshotForDirty = (d = {}) => JSON.stringify({
+ name: (d.name || '').trim(),
+ starterPrompt: d.starterPrompt || '',
+ logline: d.logline || '',
+ premise: d.premise || '',
+ styleNotes: d.styleNotes || '',
+ categories: d.categories || {},
+ compositeSheets: d.compositeSheets || [],
+ influences: ensureInfluences(d.influences),
+ locked: d.locked || {},
+ llm: d.llm || { provider: null, model: null },
+});
+
// Renders a small lock-toggle button to the right of a field label. The user
// clicks it to pin a field against AI refinement/expansion. The icon flips
@@ -562,6 +578,18 @@ export default function UniverseBuilder() {
// categories instead of the stale closure value.
const draftRef = useRef(null);
useEffect(() => { draftRef.current = draft; }, [draft]);
+ // Server-side baseline of the draft. LLM-driven mutators (auto-sort /
+ // promote / generate) compare current draft against this baseline and
+ // flush via handleSave() when they diverge so the server doesn't operate
+ // on a stale copy.
+ const savedDraftSnapshotRef = useRef(draftSnapshotForDirty(emptyTemplate()));
+ const markDraftSaved = useCallback((snapshotSource) => {
+ savedDraftSnapshotRef.current = draftSnapshotForDirty(snapshotSource);
+ }, []);
+ const isDraftDirty = useCallback(
+ () => savedDraftSnapshotRef.current !== draftSnapshotForDirty(draftRef.current || draft),
+ [draft],
+ );
// Page-level in-flight gate for the promote action. Ref + state pair so
// the disable check stays synchronous (ref) while still triggering renders
// (state). Promote writes to `universe[bibleField]` and `categories[key]`
@@ -662,7 +690,9 @@ export default function UniverseBuilder() {
setCanonDirty(false);
clearPendingCanonAdditions();
if (!selectedId) {
- setDraft(emptyTemplate());
+ const empty = emptyTemplate();
+ setDraft(empty);
+ markDraftSaved(empty);
setRuns([]);
return;
}
@@ -673,7 +703,7 @@ export default function UniverseBuilder() {
]).then(([w, r]) => {
if (cancelled) return;
if (w) {
- setDraft({
+ const hydrated = {
...w,
// Ensure starter buckets exist, but preserve custom buckets returned
// by the LLM or added by the user.
@@ -685,7 +715,9 @@ export default function UniverseBuilder() {
influences: ensureInfluences(w.influences),
locked: w.locked || {},
llm: w.llm || { provider: null, model: null },
- });
+ };
+ setDraft(hydrated);
+ markDraftSaved(hydrated);
}
setRuns(r);
});
@@ -735,7 +767,7 @@ export default function UniverseBuilder() {
const handleSave = async () => {
if (!draft.name?.trim()) {
toast.error('Name is required');
- return;
+ return null;
}
setSaving(true);
const basePayload = {
@@ -778,7 +810,7 @@ export default function UniverseBuilder() {
if (!fresh) {
setSaving(false);
toast.error('Save failed: could not fetch latest canon — please try again');
- return;
+ return null;
}
const additions = pendingCanonAdditionsRef.current;
const baseCanon = {
@@ -805,6 +837,7 @@ export default function UniverseBuilder() {
setCanonDirty(false);
clearPendingCanonAdditions();
}
+ markDraftSaved(payload);
toast.success(selectedId ? 'World updated' : 'World created');
setWorlds((prev) => {
const without = prev.filter((w) => w.id !== result.id);
@@ -815,6 +848,7 @@ export default function UniverseBuilder() {
// navigating is harmless (replace-style).
if (result.id !== selectedId) goToWorld(result.id);
}
+ return result;
};
const handleDelete = async () => {
@@ -1085,6 +1119,7 @@ export default function UniverseBuilder() {
// those entries are now on the server.
setCanonDirty(false);
clearPendingCanonAdditions();
+ markDraftSaved(payload);
// New record: route to its id so the canon section gates flip and
// subsequent draft state reflects the persisted record.
if (!selectedId) goToWorld(saved.id);
@@ -1128,7 +1163,7 @@ export default function UniverseBuilder() {
if (Array.isArray(patch.compositeSheets)) next.compositeSheets = patch.compositeSheets;
setDraft(next);
if (selectedId && next.name?.trim()) {
- const updated = await updateUniverse(selectedId, {
+ const refinePayload = {
name: next.name.trim(),
starterPrompt: next.starterPrompt || '',
logline: next.logline || '',
@@ -1139,12 +1174,15 @@ export default function UniverseBuilder() {
influences: ensureInfluences(next.influences),
locked: next.locked || {},
llm: next.llm || {},
- }).catch((e) => { toast.error(`Auto-save after refine failed: ${e.message}`); return null; });
+ };
+ const updated = await updateUniverse(selectedId, refinePayload)
+ .catch((e) => { toast.error(`Auto-save after refine failed: ${e.message}`); return null; });
if (updated) {
setWorlds((prev) => {
const without = prev.filter((w) => w.id !== updated.id);
return [updated, ...without];
});
+ markDraftSaved(refinePayload);
}
}
};
@@ -1402,12 +1440,21 @@ export default function UniverseBuilder() {
// single atomic patch server-side so the universe ends up consistent or
// unchanged. Renames the LLM suggests are surfaced in the toast but not
// auto-applied (the user can rename manually if they want it).
+ // Returns true when the draft is clean or save succeeded; false (with
+ // handleSave's own error toast already raised) when save failed.
+ const flushDraftIfDirty = useCallback(async () => {
+ if (!isDraftDirty()) return true;
+ const saved = await handleSave();
+ return !!saved;
+ }, [isDraftDirty]);
+
const handleAutoSort = () => runUniverseAction({
ref: autoSortingRef,
setBusy: setAutoSorting,
loadingMessage: 'Auto-sorting buckets with AI…',
errorPrefix: 'Auto-sort failed',
notSavedMessage: 'Save the universe first — auto-sort needs the persisted record',
+ preflight: flushDraftIfDirty,
action: (capturedId) => autoSortBuckets(capturedId, {
providerId: draft.llm?.provider || undefined,
model: draft.llm?.model || undefined,
@@ -1417,19 +1464,22 @@ export default function UniverseBuilder() {
// Merge only the reclassified buckets into the draft — wholesale-
// replacing `categories` with the server snapshot would discard any
// user edits to OTHER buckets made while the LLM call was in flight.
+ // Compute the merge from draftRef so React strict-mode's double-fire
+ // of state updaters doesn't double-stringify the dirty baseline.
const sortedKeys = new Set((result.results || []).map((r) => r.sourceKey));
- setDraft((d) => {
- const next = { ...(d.categories || {}) };
- for (const key of sortedKeys) {
- if (updated.categories?.[key]) next[key] = updated.categories[key];
- }
- return {
- ...d,
- categories: next,
- schemaVersion: updated.schemaVersion,
- updatedAt: updated.updatedAt,
- };
- });
+ const baseDraft = draftRef.current || draft;
+ const nextCategories = { ...(baseDraft.categories || {}) };
+ for (const key of sortedKeys) {
+ if (updated.categories?.[key]) nextCategories[key] = updated.categories[key];
+ }
+ const newDraft = {
+ ...baseDraft,
+ categories: nextCategories,
+ schemaVersion: updated.schemaVersion,
+ updatedAt: updated.updatedAt,
+ };
+ setDraft(newDraft);
+ markDraftSaved(newDraft);
const sortedCount = result.results?.length || 0;
const renames = (result.results || []).filter((r) => r.suggestedKey);
const summary = sortedCount
@@ -1443,6 +1493,10 @@ export default function UniverseBuilder() {
});
const handleGenerateInCategory = async (cat, count) => {
+ // Match the runUniverseAction-based handlers — flush dirty draft so the
+ // subsequent auto-save can't clobber unrelated fields with a stale spread.
+ const flushed = await flushDraftIfDirty();
+ if (!flushed) return;
const current = draft.categories?.[cat]?.variations || [];
const existingLabels = current.map((v) => v.label).filter(Boolean);
const result = await generateCategoryVariations({
@@ -1480,6 +1534,7 @@ export default function UniverseBuilder() {
const without = prev.filter((w) => w.id !== updated.id);
return [updated, ...without];
});
+ markDraftSaved(nextDraft);
toast.success(`Added ${additionCount} variation${additionCount === 1 ? '' : 's'} to ${humanizeCategory(cat)} — saved`);
return;
}
@@ -1498,6 +1553,7 @@ export default function UniverseBuilder() {
loadingMessage: `Promoting "${variation.label}" to canon…`,
errorPrefix: 'Promote failed',
notSavedMessage: 'Save the universe first — promote needs the persisted record',
+ preflight: flushDraftIfDirty,
action: (capturedId) => promoteVariationToCanon(capturedId, {
category,
label: variation.label,
@@ -1510,15 +1566,20 @@ export default function UniverseBuilder() {
// Selective merge: only the canon array + the affected category bucket
// changed server-side. Preserve every other draft field (the user may
// have typed into logline/premise/influences during the LLM call).
- setDraft((d) => ({
- ...d,
+ // Compute outside setDraft so strict-mode's double-invoke doesn't
+ // re-stringify the dirty baseline.
+ const baseDraft = draftRef.current || draft;
+ const newDraft = {
+ ...baseDraft,
characters: updated.characters,
settings: updated.settings,
objects: updated.objects,
- categories: { ...d.categories, [result.removed.category]: updated.categories?.[result.removed.category] },
+ categories: { ...baseDraft.categories, [result.removed.category]: updated.categories?.[result.removed.category] },
schemaVersion: updated.schemaVersion,
updatedAt: updated.updatedAt,
- }));
+ };
+ setDraft(newDraft);
+ markDraftSaved(newDraft);
return `Promoted "${variation.label}" → ${result.targetKind} canon`;
},
});
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 633b14d85b..859f9b797b 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -780,17 +780,42 @@ export async function insertUniverseWithId(input = {}) {
});
}
-export async function updateUniverse(id, patch = {}) {
+export async function updateUniverse(id, patchOrMutator = {}) {
// 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 () => {
+ //
+ // `patchOrMutator` overloads:
+ // - Plain object: patch is applied directly inside the queue (legacy).
+ // - `async (latest) => patch | null`: mutator runs INSIDE the queue with
+ // the freshest persisted record so callers whose read-modify-write
+ // straddles a slow LLM call can't race a concurrent edit. Returning
+ // `null`/`undefined` short-circuits the write and resolves with the
+ // unchanged record (no `updatedAt` bump, no rename cascade, no
+ // `recordUpdated` emit).
+ const isMutator = typeof patchOrMutator === 'function';
+ const { merged, nameChanged, skipped } = 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];
+ let patch;
+ if (isMutator) {
+ patch = await patchOrMutator(cur);
+ if (patch === null || patch === undefined) {
+ return { merged: cur, nameChanged: false, skipped: true };
+ }
+ // `typeof === 'object'` matches arrays and null — reject both so a stray
+ // `return []` can't slip through and silently no-op the categories merge.
+ if (Array.isArray(patch) || typeof patch !== 'object') {
+ throw makeErr('updateUniverse mutator must return a plain object or null', ERR_VALIDATION);
+ }
+ } else {
+ patch = patchOrMutator;
+ }
+
// 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.
@@ -846,8 +871,9 @@ export async function updateUniverse(id, patch = {}) {
if (!mergedRecord) throw makeErr('Invalid universe payload', ERR_VALIDATION);
state.universes[idx] = mergedRecord;
await writeState(state);
- return { merged: mergedRecord, nameChanged: mergedRecord.name !== cur.name };
+ return { merged: mergedRecord, nameChanged: mergedRecord.name !== cur.name, skipped: false };
});
+ if (skipped) return merged;
// 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.
// Runs OUTSIDE the queue so the media-collections write tail can't stall
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 3aae74d58d..a4311742b2 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -259,6 +259,61 @@ describe("universeBuilder service", () => {
).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
+ it("updateUniverse accepts a mutator(latest) callback that runs inside the queue", async () => {
+ const w = await seedWorld({ logline: "before" });
+ const mutator = vi.fn(async (latest) => {
+ expect(latest.id).toBe(w.id);
+ return { logline: `${latest.logline} → after` };
+ });
+ const patched = await svc.updateUniverse(w.id, mutator);
+ expect(mutator).toHaveBeenCalledTimes(1);
+ expect(patched.logline).toBe("before → after");
+ });
+
+ it("updateUniverse short-circuits with no write when the mutator returns null", async () => {
+ const w = await seedWorld();
+ const beforeUpdatedAt = w.updatedAt;
+ const patched = await svc.updateUniverse(w.id, async () => null);
+ // No write happened: updatedAt unchanged, no rename cascade fired.
+ expect(patched.updatedAt).toBe(beforeUpdatedAt);
+ expect(patched.id).toBe(w.id);
+ });
+
+ it("updateUniverse mutator that throws propagates without writing", async () => {
+ const w = await seedWorld({ logline: "untouched" });
+ await expect(
+ svc.updateUniverse(w.id, async () => { throw new Error("mutator boom"); }),
+ ).rejects.toThrow("mutator boom");
+ const fresh = await svc.getUniverse(w.id);
+ expect(fresh.logline).toBe("untouched");
+ });
+
+ it("updateUniverse mutator returning a non-object value throws ERR_VALIDATION", async () => {
+ const w = await seedWorld();
+ await expect(
+ svc.updateUniverse(w.id, async () => "not-an-object"),
+ ).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ // Arrays are `typeof 'object'` but would silently no-op the categories
+ // merge — reject them explicitly.
+ await expect(
+ svc.updateUniverse(w.id, async () => []),
+ ).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it("updateUniverse mutator sees concurrent writes that landed before it ran (queued)", async () => {
+ const w = await seedWorld({ logline: "v0" });
+ // Two updates issued in parallel against the same record. The queue
+ // serializes them: the mutator sees the result of the first write.
+ const [first, second] = await Promise.all([
+ svc.updateUniverse(w.id, { logline: "v1" }),
+ svc.updateUniverse(w.id, async (latest) => ({
+ logline: `${latest.logline}+v2`,
+ })),
+ ]);
+ expect(first.logline).toBe("v1");
+ expect(second.logline).toBe("v1+v2");
+ });
+
it("updateUniverse cascades a name change onto the linked media collection", async () => {
const collections = await import("./mediaCollections.js");
const w = await seedWorld();
diff --git a/server/services/universeBuilderAutoSort.js b/server/services/universeBuilderAutoSort.js
index 67e2293045..476c07e409 100644
--- a/server/services/universeBuilderAutoSort.js
+++ b/server/services/universeBuilderAutoSort.js
@@ -175,61 +175,66 @@ export async function autoSortOtherBuckets(universeId, options = {}) {
const classifications = extractClassifications(raw);
- // Re-fetch the latest universe state immediately before the write so
- // concurrent edits made to OTHER buckets (in another tab) during the
- // LLM call aren't overwritten. We still build the patch keyed only on
- // the buckets the LLM classified, but each bucket's spread uses the
- // freshest persisted shape — so a variation added mid-LLM-call to a
- // bucket that's about to be reclassified is preserved.
- const latest = await getUniverse(universeId);
- const latestCategories = latest.categories || {};
- const byKey = new Map(
- Object.entries(latestCategories)
- .filter(([, c]) => c && c.kind === 'other')
- .map(([key, c]) => [key, c]),
- );
- const categoriesPatch = {};
- const results = [];
- const seenSourceKeys = new Set();
-
- for (const c of classifications) {
- // Defensive per-entry kind gate. The shape predicate above only filters
- // which parsed block extractJson returns — when only one block parses,
- // it's returned as a fallback even if its entries fail the predicate.
- // Without this guard a hallucinated `kind: "magic"` would flow into the
- // categories patch and the universe sanitizer would silently coerce it
- // to 'other', undoing the auto-sort the user just ran.
- if (!c || typeof c !== 'object') continue;
- if (typeof c.key !== 'string') continue;
- if (!SORTABLE_KINDS.includes(c.kind)) continue;
- const sourceKey = normalizeCategoryKey(c.key);
- if (!sourceKey || seenSourceKeys.has(sourceKey)) continue;
- // Drop classifications for buckets that no longer exist or are no
- // longer kind:'other' on the latest state — a concurrent assignBucketKind
- // or removeCategory call would otherwise be silently reverted here.
- const latestBucket = byKey.get(sourceKey);
- if (!latestBucket) continue;
- seenSourceKeys.add(sourceKey);
-
- // updateUniverse does per-key replacement on categories (not per-field
- // merge), so spread the whole latest bucket record to preserve any
- // variations / fields added mid-flight.
- categoriesPatch[sourceKey] = { ...latestBucket, kind: c.kind };
-
- const suggested = typeof c.suggestedKey === 'string' ? normalizeCategoryKey(c.suggestedKey) : '';
- const suggestedKey = (suggested && suggested !== sourceKey) ? suggested : null;
-
- results.push({ sourceKey, kind: c.kind, suggestedKey });
- }
-
- if (results.length === 0) {
- throw new ServerError(
- 'LLM returned no valid classifications for any bucket. Try a different model or rerun.',
- { status: 502, code: 'UNIVERSE_AUTOSORT_NO_CLASSIFICATIONS' },
+ // Resolve classifications into a patch INSIDE the write queue so the
+ // read-modify-write straddling the LLM call can't lose a concurrent edit.
+ // The mutator receives the freshest persisted record and rebuilds the
+ // categories patch keyed off the latest `kind: 'other'` buckets — bucket
+ // spreads use the latest variations[] so a variation added mid-LLM-call
+ // is preserved; reclassifications targeting buckets the user deleted or
+ // already auto-sorted from another tab are dropped silently.
+ let results = [];
+ const updated = await updateUniverse(universeId, async (latest) => {
+ const latestCategories = latest.categories || {};
+ const byKey = new Map(
+ Object.entries(latestCategories)
+ .filter(([, c]) => c && c.kind === 'other')
+ .map(([key, c]) => [key, c]),
);
- }
+ const categoriesPatch = {};
+ const seenSourceKeys = new Set();
+ const localResults = [];
+
+ for (const c of classifications) {
+ // Defensive per-entry kind gate. The shape predicate above only filters
+ // which parsed block extractJson returns — when only one block parses,
+ // it's returned as a fallback even if its entries fail the predicate.
+ // Without this guard a hallucinated `kind: "magic"` would flow into the
+ // categories patch and the universe sanitizer would silently coerce it
+ // to 'other', undoing the auto-sort the user just ran.
+ if (!c || typeof c !== 'object') continue;
+ if (typeof c.key !== 'string') continue;
+ if (!SORTABLE_KINDS.includes(c.kind)) continue;
+ const sourceKey = normalizeCategoryKey(c.key);
+ if (!sourceKey || seenSourceKeys.has(sourceKey)) continue;
+ // Drop classifications for buckets that no longer exist or are no
+ // longer kind:'other' on the latest state — a concurrent
+ // assignBucketKind or removeCategory call would otherwise be silently
+ // reverted here.
+ const latestBucket = byKey.get(sourceKey);
+ if (!latestBucket) continue;
+ seenSourceKeys.add(sourceKey);
- const updated = await updateUniverse(universeId, { categories: categoriesPatch });
+ // updateUniverse does per-key replacement on categories (not per-field
+ // merge), so spread the whole latest bucket record to preserve any
+ // variations / fields added mid-flight.
+ categoriesPatch[sourceKey] = { ...latestBucket, kind: c.kind };
+
+ const suggested = typeof c.suggestedKey === 'string' ? normalizeCategoryKey(c.suggestedKey) : '';
+ const suggestedKey = (suggested && suggested !== sourceKey) ? suggested : null;
+
+ localResults.push({ sourceKey, kind: c.kind, suggestedKey });
+ }
+
+ if (localResults.length === 0) {
+ throw new ServerError(
+ 'LLM returned no valid classifications for any bucket. Try a different model or rerun.',
+ { status: 502, code: 'UNIVERSE_AUTOSORT_NO_CLASSIFICATIONS' },
+ );
+ }
+
+ results = localResults;
+ return { categories: categoriesPatch };
+ });
console.log(
`🪄 Universe Builder auto-sort complete — universe=${universeId.slice(0, 8)} classified=${results.length} runId=${runId.slice(0, 8)}`,
diff --git a/server/services/universeBuilderPromote.js b/server/services/universeBuilderPromote.js
index 8f31cde146..99333661ae 100644
--- a/server/services/universeBuilderPromote.js
+++ b/server/services/universeBuilderPromote.js
@@ -105,6 +105,27 @@ ${outputContract}
- Stay tonally consistent with the LOGLINE / STYLE NOTES / EMBRACE INFLUENCES above when present.`;
};
+// Find a canon entry that collides with `label` (and, for settings, the
+// slugline derived from `label` or `secondarySlug`). Run pre-LLM against
+// the prompt-building snapshot AND post-LLM against the latest persisted
+// canon — keeps the duplicate-detection logic in one place.
+const findCanonCollision = (canon, label, targetKind, secondarySlug = '') => {
+ const direct = findBibleEntryByName(canon, label);
+ if (direct) return direct;
+ if (targetKind !== 'settings') return null;
+ const needleSlug = normalizeSlugline(label);
+ const secondary = normalizeSlugline(secondarySlug);
+ if (!needleSlug && !secondary) return null;
+ return canon.find((e) => {
+ if (!e || typeof e !== 'object') return false;
+ const eSlug = normalizeSlugline(e.slugline);
+ const eName = normalizeSlugline(e.name);
+ if (needleSlug && (eSlug === needleSlug || eName === needleSlug)) return true;
+ if (secondary && (eSlug === secondary || eName === secondary)) return true;
+ return false;
+ }) || null;
+};
+
const extractEntryJson = (raw, kind) => {
if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');
const predicate = SHAPE_PREDICATE[kind] || isCharacterShape;
@@ -204,18 +225,7 @@ export async function promoteVariationToCanon(universeId, options = {}) {
// dash-variant or slug-vs-name promotion doesn't slip past name-only
// matching.
const existingCanon = Array.isArray(universe[bibleField]) ? universe[bibleField] : [];
- let collision = findBibleEntryByName(existingCanon, variation.label);
- if (!collision && targetKind === 'settings') {
- const needleSlug = normalizeSlugline(variation.label);
- if (needleSlug) {
- collision = existingCanon.find((e) => {
- if (!e || typeof e !== 'object') return false;
- if (normalizeSlugline(e.slugline) === needleSlug) return true;
- if (normalizeSlugline(e.name) === needleSlug) return true;
- return false;
- });
- }
- }
+ const collision = findCanonCollision(existingCanon, variation.label, targetKind);
if (collision) {
throw new ServerError(
`Canon ${targetKind} "${variation.label}" already exists — rename the variation or open the existing entry`,
@@ -278,15 +288,61 @@ export async function promoteVariationToCanon(universeId, options = {}) {
// Build the patch: append the new canon entry + drop the source variation
// from its bucket. Both writes go through one updateUniverse so the
// transition is atomic (success = entry in canon AND variation gone).
- const nextCanon = [...existingCanon, sanitized];
- const nextVariations = variations.filter((_, i) => i !== sourceIdx);
- const patch = {
- [bibleField]: nextCanon,
- categories: {
- [categoryKey]: { kind: bucket.kind, variations: nextVariations },
- },
- };
- const updated = await updateUniverse(universeId, patch);
+ //
+ // The mutator runs INSIDE the file-level write queue so a concurrent edit
+ // between the (pre-LLM) duplicate check and the persist can't slip a
+ // colliding canon entry in, and the source variation is re-located by
+ // label on the freshest persisted bucket — the original `sourceIdx` is
+ // stale once the queue releases.
+ const updated = await updateUniverse(universeId, async (latest) => {
+ const latestBucket = latest.categories?.[categoryKey];
+ if (!latestBucket) {
+ throw new ServerError(
+ `Category "${categoryKey}" was deleted while promoting — re-open the universe and try again`,
+ { status: 409, code: 'UNIVERSE_PROMOTE_CATEGORY_GONE' },
+ );
+ }
+ const latestVariations = Array.isArray(latestBucket.variations) ? latestBucket.variations : [];
+ // Re-locate by label (case-insensitive). The pre-LLM `sourceIdx` is
+ // stale — concurrent edits could have reordered or removed entries.
+ const latestSourceIdx = latestVariations.findIndex(
+ (v) => typeof v?.label === 'string' && v.label.toLowerCase() === needle,
+ );
+ if (latestSourceIdx < 0) {
+ throw new ServerError(
+ `Variation "${rawLabel}" was removed from bucket "${categoryKey}" during promotion`,
+ { status: 409, code: 'UNIVERSE_PROMOTE_VARIATION_GONE' },
+ );
+ }
+ // Re-check the duplicate-name collision against the LATEST canon — a
+ // concurrent promote (or manual canon add) in another tab could have
+ // landed an entry with the same name while the LLM was thinking. The
+ // sanitized entry's slugline is included as a secondary key for the
+ // settings case, since the LLM might have emitted a clean slugline
+ // that collides with an existing entry whose name doesn't match.
+ const latestCanon = Array.isArray(latest[bibleField]) ? latest[bibleField] : [];
+ const lateCollision = findCanonCollision(latestCanon, sanitized.name, targetKind, sanitized.slugline);
+ if (lateCollision) {
+ throw new ServerError(
+ `Canon ${targetKind} "${sanitized.name}" already exists — rename the variation or open the existing entry`,
+ {
+ status: 409,
+ code: 'UNIVERSE_PROMOTE_DUPLICATE',
+ context: { details: { existingId: lateCollision.id } },
+ },
+ );
+ }
+
+ return {
+ [bibleField]: [...latestCanon, sanitized],
+ categories: {
+ [categoryKey]: {
+ kind: latestBucket.kind,
+ variations: latestVariations.filter((_, i) => i !== latestSourceIdx),
+ },
+ },
+ };
+ });
// updateUniverse re-runs sanitizers; pull the merged entry back out by
// id so the response reflects the canonical persisted shape.
const persisted = (updated[bibleField] || []).find((e) => e.id === sanitized.id) || sanitized;