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

docs([extract-useuniverseaction-hook]): archive to DONE.md

[._.]/ Adam Eivyd48a6cba8e93
diff --git a/DONE.md b/DONE.md
index e94ba88ee3..2281b8b14e 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
+- **[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.
- **[auto-sort-with-ai-llm-classify-each-kind-other] Universe Builder — Auto-sort with AI.** New `POST /api/universe-builder/:id/auto-sort` (server: `server/services/universeBuilderAutoSort.js`, `server/routes/universeBuilder.js`) batches every `kind: 'other'` bucket into a single LLM call that returns `{ classifications: [{ key, kind, suggestedKey? }] }`. The service applies kind reassignments atomically via one `updateUniverse` patch (defensive per-entry kind gate filters hallucinated kinds); `suggestedKey` renames stay opt-in — they surface as a count in the success toast but the bucket key isn't auto-renamed. Replaces the Other-tab's toast-stub `onAutoSort` handler with a real spinner-driven handler in `client/src/pages/UniverseBuilder.jsx`; new `autoSortBuckets` API helper in `client/src/services/apiUniverseBuilder.js`. Concurrent-edit safety: the service re-fetches the latest universe state immediately before the write so a variation added to a soon-to-be-classified bucket in another tab during the LLM call isn't overwritten; the client merges only the reclassified buckets into the draft to preserve user edits to other buckets. Covered by 16 unit tests in `universeBuilderAutoSort.test.js` (happy path, no-other-buckets short-circuit, hallucinated-key filter, `LLM_INVALID_JSON` (empty response + no-parse + non-array `classifications`) vs `NO_CLASSIFICATIONS` paths, `NO_PROVIDER` gate, prompt-injection defense — ASCII newlines pinned on labels + styleNotes + logline; Unicode LS/PS/NEL + form feed + vertical tab pinned on labels, logline, and styleNotes) + 4 route tests in `universeBuilder.test.js` + 2 client tests in `UniverseBuilder.test.jsx` for `OtherTab` (Auto-sort button fires `onAutoSort` when enabled; disabled with "Sorting…" label while `autoSorting=true`).
diff --git a/PLAN.md b/PLAN.md
index c637cc673a..410c861ef7 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -12,7 +12,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- **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):**
- - [ ] [extract-useuniverseaction-hook] **Extract `useUniverseAction({ selectedId, mountedRef, setWorlds, setDraft })` hook.** `handlePromoteVariation`, `handleAutoSort`, and (to a lesser extent) `handleGenerateInCategory` in `client/src/pages/UniverseBuilder.jsx` share the same `*Ref` re-entrancy guard → `capturedId = selectedId` → `toast.loading` → API call → `mountedRef && capturedId === selectedId` stale-write guard → `setWorlds` + selective `setDraft` skeleton. `useAsyncAction` is too thin — it doesn't model the stale-write guard CLAUDE.md calls out. Extract when a 4th LLM-driven handler lands.
- [ ] [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).
2. **Step-by-step approval/lock UX across Universe → Series → Arc → Seasons → Episodes.** Iteration 1 shipped a single arc-level lock; extend to per-season + per-field locks, lock the bulk runners, surface stage-progress strip, enforce locks server-side before LLM invocations.