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

feat: pick a universe to style renders from the Quick Image widget

[._.]/ Adam Eivy5c59ed0ee7dd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 428bec50a0..4eb1f4da72 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -223,3 +223,5 @@
- **[issue-3050] Spread walk-cycle phases evenly when the gait period doesn't divide the frame count** — a re-derived walk could read as a limp rather than a smooth loop: the *timing* was uneven, not the seam (which is why `validation` never flagged it — the loop closed fine). `selectCycleIndices` resamples the detected window with `pyRound(i * cycleLength / frameCount)`, and `pyRound` is Python's round-half-to-even, so a `.5` tie breaks toward the even integer — meaning the tie's *direction* depends on the parity of the integer part and consecutive ties resolve opposite ways. A 15-frame gait over 12 phases landed its ties at 2.5→2 (down), 7.5→8 (up), 12.5→12 (down), putting double-steps at positions 2, 5 and 10 — spacings of 3 and 5, an arrhythmic hitch. The run manifest corroborated it: those three transitions carried ~28% more motion than the single-step median. Phase indices are now distributed with integer half-up (`floor((i * cycleLength + frameCount/2) / frameCount)`), which resolves every tie the same way, so the unavoidable stretch is spread evenly — 15→12 moves its double-steps to 1, 5 and 9 (gaps of 4 and 4). This is the one place that deliberately does not use `pyRound`: the pixel math keeps it for byte-compatibility with the source pipeline, while phase selection is a perceptual-quality question and only it has a tie problem. The legacy 12→8 default was affected too (strides `2,1,1,2,2,1,1` → `2,1,2,1,2,1,2`), as were 18→12 and any other ratio landing ties at regular intervals; 16→12, 13→12 and 12→12 were already even and are unchanged. The old golden-array test asserted the banker's-rounding output directly; it is replaced by a property assertion — at most two distinct stride lengths, differing by 1, with the longer ones evenly spaced — checked across five ratios so a future change to the resample has to preserve it for all of them.
- **[issue-3052] Stop the requested phase count from hiding a shorter gait period** — a walk read as janky leg movement (the legs visibly jump mid-loop) even though the endpoint seam scored well and validation passed. `selectCycleIndices` searched only windows of at least `frameCount`, on the grounds that a shorter one cannot yield that many *distinct* source frames — but that floor also made any gait whose real period is shorter **invisible to the detector**. On a real clip the gait ran 11 frames against 12 requested phases, so the search could only offer a 15-frame window: **1.36 gait cycles**, which replays a third of a stride. It scored well because a front-facing walk is near-symmetric, so 15 frames lands on the *mirrored* pose and an image-distance metric reads that as the same one — `endpointSeamScore` 0.53 while the legs were plainly wrong. The detector now probes for the true period without the output-count floor and prefers it when it is only mildly shorter (`MIN_PERIOD_RATIO = 0.8`), holding one frame to reach the requested count: a far smaller artifact than replaying part of a stride, and bounded so a much shorter period still falls back to the longer window. `cycleSelection.heldFrames` records how many phases repeat, and `validateFrames` takes it so an intentional hold is not confused with the "packer picked the same frame twice" failure that guard exists for. Across one character's seven directions the probe found better (lower-seam) windows on five — south 15→11 (0.531→0.476), south-east 12→11 (1.082→**0.438**), north-east 12→11 (0.985→**0.600**). **Rejected on evidence:** re-extracting at `WALK_FPS * frameCount / period` so the period lands exactly on the count was built and measured, and is wrong twice over — ffmpeg's `fps` filter picks the nearest source frame, so any rate that is not `sourceFps / k` samples unevenly (13.09fps from a 24fps source gives source-frame steps `[2,2,2,1,2,2,2,2,2,1,2,2]`, widening the adjacent-motion range from 2.2× to 11×), and extracting denser gains nothing because the clip is 12fps content encoded at 24fps with every frame duplicated (adjacent scores at 24fps alternate `1.29, 0.21, 2.65, 0.10…`). `WALK_FPS = 12` is already the native content rate, so an 11-frame period genuinely cannot yield 12 distinct phases.
- **[issue-3044] Let a clipless imported walk direction be reopened for regeneration** — per-direction Reopen now uses the same server resolver and informed `acknowledgeNoClips` escape as set-wide Unlock, with the `{ blocked, stranded, acknowledgeable }` result stamped on its run. A blocked card explains the one-new-render cost and offers an inline **Reopen anyway** confirmation when its locked anchor makes regeneration safe; otherwise it shows no guaranteed-409 control. The copy is shared with the Unlock panel, so their cost and recovery wording stay in sync.
+- **Save the Universe Builder draft before a batch render** — `/render` compiles prompts from the *persisted* universe, but every count and label in the render scope came from the in-memory draft. Adding a landscape (or any variation) and clicking Render before saving therefore 400'd with "No prompts to render — add canon entries, variations, or composite sheets first", and editing an existing variation's prompt silently rendered the stale text. `useUniverseRender` now flushes a dirty draft through the same `flushDraftIfDirty` preflight the LLM actions already used, and aborts the render when that save fails.
+- **Pick a universe to style renders from the Quick Image dashboard widget** — the widget gains a "Universe style" dropdown that prefixes the prompt with that universe's embrace tokens and appends its avoid tokens to the negative, using the same `composeStyledPrompt` composition the Universe Builder's canon renders use. The selection persists across dashboard visits, is carried into the "Edit" handoff to the Image Gen page, and is ignored if the universe is later deleted. Backed by a new `GET /api/universe-builder/styles` that projects to `{ id, name, embrace[], avoid[] }` in SQL — the widget mounts on every dashboard visit and the full universe list ships every canon bible.
diff --git a/client/src/components/QuickImagePrompt.jsx b/client/src/components/QuickImagePrompt.jsx
index 5e992819ee..c927b0a9b7 100644
--- a/client/src/components/QuickImagePrompt.jsx
+++ b/client/src/components/QuickImagePrompt.jsx
@@ -1,9 +1,13 @@
-import { useState, useRef } from 'react';
+import { useState, useRef, useEffect, useMemo } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Sparkles, Pencil, ChevronDown, ChevronRight } from 'lucide-react';
-import { generateImage } from '../services/api';
+import { generateImage, listUniverseStyles } from '../services/api';
import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';
import { RESOLUTIONS, MAX_IMAGE_EDGE, MAX_IMAGE_PIXELS } from '../lib/imageGenResolutions';
+import { composeStyledPrompt } from '../lib/composeStyledPrompt';
+import { universeStylePreset } from '../lib/universeStylePreset';
+import { useLocalStoragePersisted } from '../hooks/useLocalStorageBool';
+import useMounted from '../hooks/useMounted';
import ResolutionField from './media/ResolutionField';
import MediaJobThumb from './pipeline/MediaJobThumb';
import toast from './ui/Toast';
@@ -20,6 +24,9 @@ export default function QuickImagePrompt() {
const [showNegative, setShowNegative] = useState(false);
const [width, setWidth] = useState(1024);
const [height, setHeight] = useState(1024);
+ const [universeStyles, setUniverseStyles] = useState([]);
+ const [universeId, setUniverseId] = useLocalStoragePersisted('dashboard.quickImage.universeId', '');
+ const mountedRef = useMounted();
// The current/last submission. `jobId` set → async backend (local/codex):
// render the live MediaJobThumb so the user sees the diffusion spinner →
// final image, exactly like the Universe asset slots. `filename` only →
@@ -29,6 +36,28 @@ export default function QuickImagePrompt() {
const submittingRef = useRef(false);
const navigate = useNavigate();
+ // Every row is selectable — the endpoint already drops universes with no
+ // style tokens. Failure is non-fatal: the picker stays hidden and the widget
+ // behaves exactly as it did before.
+ useEffect(() => {
+ listUniverseStyles({ silent: true })
+ .then((rows) => { if (mountedRef.current) setUniverseStyles(Array.isArray(rows) ? rows : []); })
+ .catch(() => { /* non-fatal — widget degrades to un-styled quick renders */ });
+ }, [mountedRef]);
+
+ // The selected universe's `{ prompt, negativePrompt }` preset, or null when
+ // nothing is selected — including when the saved id no longer resolves, so a
+ // deleted universe can't keep silently styling renders.
+ const stylePreset = useMemo(() => {
+ const match = universeId ? universeStyles.find((u) => u.id === universeId) : null;
+ return match ? universeStylePreset(match) : null;
+ }, [universeId, universeStyles]);
+
+ // Same composition the Universe Builder's canon renders use: the universe's
+ // embrace tokens PREFIX the user prompt (diffusion weights earlier tokens
+ // heaviest) and its avoid tokens append to the negative.
+ const composeForSubmit = (text) => composeStyledPrompt(text, negativePrompt, stylePreset);
+
const handleResolution = (w, h) => { setWidth(w); setHeight(h); };
const handleGenerate = async (e) => {
@@ -47,9 +76,10 @@ export default function QuickImagePrompt() {
// empty as "no negative prompt"). Preserve the input on failure so the
// user doesn't have to retype after a server error (the API helper toasts
// on its own).
+ const styled = composeForSubmit(text);
const result = await generateImage({
- prompt: text,
- negativePrompt,
+ prompt: styled.prompt,
+ negativePrompt: styled.negativePrompt,
width,
height,
}).catch(() => null);
@@ -77,10 +107,13 @@ export default function QuickImagePrompt() {
// ImageGen page's remix-param effect reads ?prompt=…&width=…&height=… on
// mount and strips them from the URL, so the widget can hand off the
// current prompt + size + negative prompt without coupling to the form's
- // internal state.
+ // internal state. Hand off the STYLED prompt so the editor opens with what
+ // Generate would have submitted — the Image Gen page has no universe picker
+ // of its own, so an un-styled handoff would silently drop the selection.
+ const styled = composeForSubmit(text);
const params = new URLSearchParams();
- if (text) params.set('prompt', text);
- if (negativePrompt) params.set('negativePrompt', negativePrompt);
+ if (styled.prompt) params.set('prompt', styled.prompt);
+ if (styled.negativePrompt) params.set('negativePrompt', styled.negativePrompt);
params.set('width', String(width));
params.set('height', String(height));
const qs = params.toString();
@@ -111,6 +144,33 @@ export default function QuickImagePrompt() {
className="flex-1 min-h-[60px] px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm resize-none"
/>
+ {/* Universe styling. Hidden entirely when no universe carries style
+ tokens — an empty dropdown is noise on a compact widget. */}
+ {universeStyles.length > 0 && (
+ <div className="shrink-0">
+ <label htmlFor="quick-image-universe" className="block text-xs font-medium text-gray-400 mb-1">
+ Universe style
+ </label>
+ <select
+ id="quick-image-universe"
+ value={universeId}
+ onChange={(e) => setUniverseId(e.target.value)}
+ disabled={isSubmitting}
+ className={`${inputCls} disabled:opacity-50`}
+ >
+ <option value="">None</option>
+ {universeStyles.map((u) => (
+ <option key={u.id} value={u.id}>{u.name}</option>
+ ))}
+ </select>
+ {stylePreset?.prompt ? (
+ <p className="mt-1 text-[11px] text-gray-500 line-clamp-2" title={stylePreset.prompt}>
+ Prefixed with: {stylePreset.prompt}
+ </p>
+ ) : null}
+ </div>
+ )}
+
{/* Shared preset dropdown + "Custom…" width/height inputs. Reuses the
same control as the full Image Gen page so the quick widget offers
custom sizes and (unlike the old inline <select>) never shows a
diff --git a/client/src/components/QuickImagePrompt.test.jsx b/client/src/components/QuickImagePrompt.test.jsx
index 4b822e878b..450b5e0914 100644
--- a/client/src/components/QuickImagePrompt.test.jsx
+++ b/client/src/components/QuickImagePrompt.test.jsx
@@ -3,34 +3,45 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import QuickImagePrompt from './QuickImagePrompt';
-// generateImage is the only network call; MediaJobThumb subscribes to sockets
-// (irrelevant to this widget's resolution wiring) so stub it to a marker.
+// generateImage + listUniverseStyles are the only network calls; MediaJobThumb
+// subscribes to sockets (irrelevant here) so stub it to a marker.
const generateImage = vi.fn();
-vi.mock('../services/api', () => ({ generateImage: (...args) => generateImage(...args) }));
+const listUniverseStyles = vi.fn();
+vi.mock('../services/api', () => ({
+ generateImage: (...args) => generateImage(...args),
+ listUniverseStyles: (...args) => listUniverseStyles(...args),
+}));
vi.mock('./pipeline/MediaJobThumb', () => ({ default: () => <div data-testid="job-thumb" /> }));
vi.mock('./ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
-const renderWidget = () =>
+// Settles the mount fetch before returning so no test has to remember to — a
+// state update from it after the test body starts trips the act() guard.
+const renderWidget = async () => {
render(
<MemoryRouter>
<QuickImagePrompt />
</MemoryRouter>,
);
+ await waitFor(() => expect(listUniverseStyles).toHaveBeenCalled());
+};
-describe('QuickImagePrompt — resolution control', () => {
- beforeEach(() => {
- generateImage.mockReset();
- generateImage.mockResolvedValue({ jobId: 'job-1', status: 'queued' });
- });
+beforeEach(() => {
+ localStorage.clear();
+ generateImage.mockReset();
+ generateImage.mockResolvedValue({ jobId: 'job-1', status: 'queued' });
+ listUniverseStyles.mockReset();
+ listUniverseStyles.mockResolvedValue([]);
+});
- it('offers a Custom… option alongside the universal presets', () => {
- renderWidget();
+describe('QuickImagePrompt — resolution control', () => {
+ it('offers a Custom… option alongside the universal presets', async () => {
+ await renderWidget();
expect(screen.getByRole('option', { name: 'Custom…' })).toBeTruthy();
expect(screen.getByRole('option', { name: '1024×1024' })).toBeTruthy();
});
it('reveals width/height inputs when Custom… is selected and generates with the typed size', async () => {
- renderWidget();
+ await renderWidget();
// Default 1024×1024 matches a preset → no custom inputs yet.
expect(screen.queryByLabelText('Width')).toBeNull();
@@ -51,8 +62,8 @@ describe('QuickImagePrompt — resolution control', () => {
);
});
- it('keeps an off-preset size visible in the inputs rather than a blank select', () => {
- renderWidget();
+ it('keeps an off-preset size visible in the inputs rather than a blank select', async () => {
+ await renderWidget();
// Land on an off-preset size via the custom flow, then confirm it round-trips
// to the visible inputs (the old inline <select> rendered a blank option).
fireEvent.change(screen.getByLabelText('Resolution'), { target: { value: '__custom__' } });
@@ -62,3 +73,57 @@ describe('QuickImagePrompt — resolution control', () => {
expect(screen.getByLabelText('Resolution').value).toBe('__custom__');
});
});
+
+describe('QuickImagePrompt — universe styling', () => {
+ const STYLES = [
+ {
+ id: 'u-1',
+ name: 'Example Universe',
+ influences: { embrace: ['inky linework', 'cold palette'], avoid: ['lowres'] },
+ },
+ ];
+
+ it('hides the picker when no universe carries style tokens', async () => {
+ await renderWidget();
+ expect(screen.queryByLabelText('Universe style')).toBeNull();
+ });
+
+ it('prefixes the prompt and appends the avoid tokens for the selected universe', async () => {
+ listUniverseStyles.mockResolvedValue(STYLES);
+ await renderWidget();
+
+ fireEvent.change(screen.getByLabelText('Universe style'), { target: { value: 'u-1' } });
+ fireEvent.change(screen.getByLabelText('Image prompt'), { target: { value: 'a quiet harbor' } });
+ fireEvent.click(screen.getByTitle('Generate with these settings'));
+
+ await waitFor(() => expect(generateImage).toHaveBeenCalled());
+ const [params] = generateImage.mock.calls[0];
+ expect(params.prompt).toBe('inky linework, cold palette. a quiet harbor');
+ expect(params.negativePrompt).toContain('lowres');
+ });
+
+ it('submits the raw prompt when the picker is left on None', async () => {
+ listUniverseStyles.mockResolvedValue(STYLES);
+ await renderWidget();
+
+ fireEvent.change(screen.getByLabelText('Image prompt'), { target: { value: 'a quiet harbor' } });
+ fireEvent.click(screen.getByTitle('Generate with these settings'));
+
+ await waitFor(() => expect(generateImage).toHaveBeenCalled());
+ expect(generateImage.mock.calls[0][0].prompt).toBe('a quiet harbor');
+ });
+
+ // A universe deleted since the selection was persisted must not keep styling
+ // renders — `stylePreset` resolves against the live list, not the saved id.
+ it('ignores a persisted selection whose universe no longer exists', async () => {
+ localStorage.setItem('dashboard.quickImage.universeId', JSON.stringify('u-gone'));
+ listUniverseStyles.mockResolvedValue(STYLES);
+ await renderWidget();
+
+ fireEvent.change(screen.getByLabelText('Image prompt'), { target: { value: 'a quiet harbor' } });
+ fireEvent.click(screen.getByTitle('Generate with these settings'));
+
+ await waitFor(() => expect(generateImage).toHaveBeenCalled());
+ expect(generateImage.mock.calls[0][0].prompt).toBe('a quiet harbor');
+ });
+});
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index b0a7a84541..2b3a8b59f0 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -19,6 +19,12 @@ export const WORLD_INFLUENCES_PER_LIST_MAX = 30;
export const listUniverses = (options = {}) => request('/universe-builder', options);
export const getUniverse = (id, options = {}) => request(`/universe-builder/${encodeURIComponent(id)}`, options);
+// `[{ id, name, influences: { embrace[], avoid[] } }]` for every live universe
+// that has style tokens. Use this instead of `listUniverses()` whenever a
+// surface only needs to layer a universe's look onto a prompt — the full list
+// ships every canon bible and category.
+export const listUniverseStyles = (options = {}) => request('/universe-builder/styles', options);
+
export const createUniverse = (data, options = {}) => request('/universe-builder', {
method: 'POST',
body: JSON.stringify(data),
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 1d60d7f6c6..0d4cc964a9 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -518,6 +518,12 @@ router.get('/duplicates', asyncHandler(async (_req, res) => {
res.json({ groups: await findDuplicateUniverseGroups() });
}));
+// Style tokens only (see svc.listUniverseStyles). Must stay ahead of `/:id` so
+// the wildcard doesn't catch "styles" as a universe id.
+router.get('/styles', asyncHandler(async (_req, res) => {
+ res.json(await svc.listUniverseStyles());
+}));
+
router.post('/merge/preview', asyncHandler(async (req, res) => {
const body = validateRequest(mergeSchema, req.body ?? {});
const preview = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices, { dryRun: true, fieldOverrides: body.fieldOverrides })
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index e496346759..8a480c46e7 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -957,6 +957,27 @@ describe('universe-builder routes', () => {
});
});
+ describe('GET /styles', () => {
+ it('returns style tokens only, and is not swallowed by /:id', async () => {
+ const app = buildApp();
+ const created = await request(app).post('/api/universe-builder').send({
+ name: 'Styled World',
+ logline: 'a logline that must NOT ship in the styles projection',
+ influences: { embrace: ['inky linework'], avoid: ['lowres'] },
+ });
+ expect(created.status).toBe(201);
+
+ const res = await request(app).get('/api/universe-builder/styles');
+ expect(res.status).toBe(200);
+ const row = res.body.find((u) => u.id === created.body.id);
+ expect(row).toEqual({
+ id: created.body.id,
+ name: 'Styled World',
+ influences: { embrace: ['inky linework'], avoid: ['lowres'] },
+ });
+ });
+ });
+
describe('duplicate resolution routes', () => {
it('GET /duplicates returns { groups: [] } (static path not swallowed by /:id)', async () => {
const res = await request(buildApp()).get('/api/universe-builder/duplicates');
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 678088700d..af4469dd5c 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -136,6 +136,45 @@ describe("universeBuilder service", () => {
expect(await svc.listUniverses()).toEqual([]);
});
+ describe("listUniverseStyles", () => {
+ it("projects to style tokens only — no categories / canon / sheets", async () => {
+ const w = await seedWorld();
+ const styles = await svc.listUniverseStyles();
+ expect(styles).toEqual([{
+ id: w.id,
+ name: "Moebius SciFi",
+ influences: {
+ embrace: ["moebius linework", "scavengers reign palette"],
+ avoid: ["blurry", "lowres"],
+ },
+ }]);
+ });
+
+ it("drops universes with no style tokens — selecting one would be a no-op", async () => {
+ await svc.createUniverse({ name: "Blank Slate" });
+ expect(await svc.listUniverseStyles()).toEqual([]);
+ });
+
+ it("folds the legacy v2 prose stylePrompt/negativePrompt into the token lists", async () => {
+ // A pre-v3 record (or one synced from an older peer) carries prose
+ // instead of chips — sanitizeTemplate splits it on read, so the
+ // projection must too or those universes look style-less.
+ await seedState({
+ universes: [{
+ id: "legacy-1",
+ name: "Legacy World",
+ stylePrompt: "ink wash, muted palette",
+ negativePrompt: "blurry",
+ }],
+ });
+ expect(await svc.listUniverseStyles()).toEqual([{
+ id: "legacy-1",
+ name: "Legacy World",
+ influences: { embrace: ["ink wash", "muted palette"], avoid: ["blurry"] },
+ }]);
+ });
+ });
+
it("createUniverse persists with sanitized categories + kind tags", async () => {
const w = await seedWorld();
expect(w.id).toBe(mockUuid(1));
@@ -741,6 +780,16 @@ describe("universeBuilder service", () => {
.toBe((await svc.listUniverses({ includeDeleted: true })).length);
});
+ it("listUniverseStyles excludes tombstones", async () => {
+ const live = await seedWorld();
+ const doomed = await seedWorld({ name: "Doomed World" });
+ expect((await svc.listUniverseStyles()).map((u) => u.id).sort())
+ .toEqual([live.id, doomed.id].sort());
+
+ await svc.deleteUniverse(doomed.id);
+ expect((await svc.listUniverseStyles()).map((u) => u.id)).toEqual([live.id]);
+ });
+
it("getUniverse returns 404 for tombstoned, includeDeleted exposes it", async () => {
const w = await seedWorld();
await svc.deleteUniverse(w.id);
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index ae0773d477..3dc4e0487e 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -17,7 +17,7 @@ import {
} from '../../lib/storyBible.js';
import { store } from './storeFacade.js';
import {
- sanitizeTemplate, sanitizeRun, sanitizeImageRefFilename,
+ sanitizeTemplate, sanitizeRun, sanitizeImageRefFilename, resolveInfluences,
makeErr, UNIVERSE_ID_RE,
ERR_NOT_FOUND, ERR_VALIDATION, ERR_DUPLICATE, ERR_HAS_LIVE_SERIES,
NAME_MAX_LENGTH, CURRENT_SCHEMA_VERSION, ENTRY_REF_KIND, IMAGE_REFS_PER_ENTRY_MAX,
@@ -77,6 +77,41 @@ export async function listUniverses({ includeDeleted = false } = {}) {
return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
+/**
+ * Every live universe as `{ id, name, influences: { embrace[], avoid[] } }` —
+ * the style tokens and nothing else.
+ *
+ * Backs the ad-hoc "style this render like universe X" pickers (the Quick Image
+ * dashboard widget) that need a universe's look but none of its canon. The PG
+ * backend projects in SQL, so this never ships the bibles / categories /
+ * composite sheets that make `listUniverses()` a multi-megabyte read — which is
+ * the whole reason to reach for this instead.
+ *
+ * The row keeps `universe.influences`' own nesting so a caller can hand it
+ * straight to `universeStylePreset(...)` like any full universe record.
+ * `resolveInfluences` is the SAME derivation `sanitizeTemplate` applies, so a
+ * projected record can't report different tokens than a full read — including
+ * for a pre-v3 record (or one synced from an older peer) whose style still
+ * lives in the legacy prose fields.
+ *
+ * Universes with no style tokens at all are dropped — selecting one would be a
+ * no-op. Newest-first, matching `listUniverses()`; ordering lives here rather
+ * than in either backend so the two can't drift.
+ */
+export async function listUniverseStyles() {
+ const rows = await store().listStyles();
+ return rows
+ .flatMap((r) => {
+ const name = trimTo(r?.name, NAME_MAX_LENGTH);
+ if (!isStr(r?.id) || !r.id || !name) return [];
+ const influences = resolveInfluences(r);
+ if (!influences.embrace.length && !influences.avoid.length) return [];
+ return [{ id: r.id, name, influences, createdAt: r.createdAt || '' }];
+ })
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id))
+ .map((r) => ({ id: r.id, name: r.name, influences: r.influences }));
+}
+
/**
* How many universes listUniverses() would return — without materializing any
* of them (#2729). A `COUNT(*)` on PG; a raw-record scan on the file backend.
diff --git a/server/services/universeBuilder/db.js b/server/services/universeBuilder/db.js
index bb0f023500..901ae7808e 100644
--- a/server/services/universeBuilder/db.js
+++ b/server/services/universeBuilder/db.js
@@ -50,6 +50,30 @@ export async function listRaw() {
return rows.map((r) => r.data);
}
+/**
+ * Live universes projected down to the style-bearing fields, unordered — the
+ * raw input `listUniverseStyles` derives its token lists from. See that
+ * function for what the projection is for and which fields feed it.
+ *
+ * `deleted = FALSE` on the mirror column, for the same reasons spelled out on
+ * `countUniverses` below (exact mirror of the JSONB flag, and the form
+ * `idx_universes_live` can serve). `name` reads the mirror column too — every
+ * `writeRaw` binds it from the same `record.name` that lands in `data`.
+ * Ordering is the service's job so both backends can't drift on it.
+ */
+export async function listStyles() {
+ const { rows } = await query(
+ `SELECT id, name,
+ data->'influences' AS influences,
+ data->>'stylePrompt' AS "stylePrompt",
+ data->>'negativePrompt' AS "negativePrompt",
+ data->>'createdAt' AS "createdAt"
+ FROM universes
+ WHERE deleted = FALSE`,
+ );
+ return rows;
+}
+
/**
* Cheap live-universe tally (#2729) — the count listUniverses().length used to
* pay for by materializing every JSONB record AND the whole run history.
diff --git a/server/services/universeBuilder/db.test.js b/server/services/universeBuilder/db.test.js
index 04cdb5a6e5..31e042c196 100644
--- a/server/services/universeBuilder/db.test.js
+++ b/server/services/universeBuilder/db.test.js
@@ -104,6 +104,33 @@ describe.skipIf(!dbReady)('universeBuilder DB adapter round-trip', () => {
expect(all.find((r) => r.id === 'u-1').logline).toBe('x');
});
+ it('listStyles projects the live set down to name + style fields', async () => {
+ await db.writeRaw('live', U('live', {
+ logline: 'a logline that must not ship',
+ influences: { embrace: ['inky linework'], avoid: ['lowres'] },
+ }));
+ await db.writeRaw('dead', U('dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));
+ await db.writeRaw('legacy', U('legacy', { stylePrompt: 'ink wash', negativePrompt: 'blurry' }));
+
+ const rows = await db.listStyles();
+ expect(rows.map((r) => r.id).sort()).toEqual(['legacy', 'live']);
+
+ const live = rows.find((r) => r.id === 'live');
+ expect(live.name).toBe('live');
+ expect(live.influences).toEqual({ embrace: ['inky linework'], avoid: ['lowres'] });
+ // The projection is the whole point — nothing else comes back. Keys must
+ // also match the file backend's row exactly (store.test.js pins that side).
+ expect(Object.keys(live).sort())
+ .toEqual(['createdAt', 'id', 'influences', 'name', 'negativePrompt', 'stylePrompt']);
+ expect(live.logline).toBeUndefined();
+
+ // Legacy v2 prose fields ride along so the service can fold them into tokens.
+ const legacy = rows.find((r) => r.id === 'legacy');
+ expect(legacy.stylePrompt).toBe('ink wash');
+ expect(legacy.negativePrompt).toBe('blurry');
+ expect(legacy.influences).toBeNull();
+ });
+
it('countUniverses counts the live set without materializing it', async () => {
// The cheap tally the character skill registry reads (#2729). It counts the
// `deleted` MIRROR COLUMN, while the service filters listUniverses() on the
diff --git a/server/services/universeBuilder/sanitize.js b/server/services/universeBuilder/sanitize.js
index 986bf7ba14..85b98ffa67 100644
--- a/server/services/universeBuilder/sanitize.js
+++ b/server/services/universeBuilder/sanitize.js
@@ -414,6 +414,24 @@ export const mergeLegacyPromptsIntoInfluences = (rawInfluences, legacyStylePromp
};
};
+/**
+ * Derive a record's `{ embrace[], avoid[] }` style tokens from ANY raw universe
+ * shape. THE single definition of that derivation — `sanitizeTemplate` (full
+ * read) and `listUniverseStyles` (the style-token projection) both call it, so
+ * a projected record can never report different tokens than a full read of the
+ * same row.
+ *
+ * Legacy v2 universes carried prose `stylePrompt` / `negativePrompt` fields
+ * alongside influences. v3 collapses both into the chip-based influences
+ * editor: split each prose field on commas/newlines and append to the matching
+ * list. `sanitizeInfluenceList` handles trim, cap, and case-insensitive dedupe
+ * so a token that already exists as a chip is not re-added by the migration.
+ * The fold MUST run before the sanitize — that ordering is the contract.
+ */
+export const resolveInfluences = (raw) => sanitizeInfluences(
+ mergeLegacyPromptsIntoInfluences(raw?.influences, raw?.stylePrompt, raw?.negativePrompt),
+);
+
// Build a refined influences object that honors per-list locks. Locked lists
// take their value from `fallback` (originals); unlocked lists take from
// `fresh` (the LLM output), falling back to `fallback` ONLY when the LLM
@@ -650,15 +668,7 @@ export const sanitizeTemplate = (raw) => {
const styleNotes = trimTo(raw.styleNotes, STYLE_NOTES_MAX);
const categories = sanitizeCategories(raw.categories || {});
const compositeSheets = sanitizeCompositeSheets(raw.compositeSheets || []);
- // Legacy v2 universes carried prose stylePrompt / negativePrompt fields
- // alongside influences. v3 collapses both into the chip-based influences
- // editor: split each prose field on commas/newlines and append to the
- // matching list. sanitizeInfluenceList handles trim, cap, and
- // case-insensitive dedupe so a token that already exists as a chip is not
- // re-added by the migration.
- const influences = sanitizeInfluences(
- mergeLegacyPromptsIntoInfluences(raw.influences, raw.stylePrompt, raw.negativePrompt),
- );
+ const influences = resolveInfluences(raw);
const locked = sanitizeLocked(raw.locked);
// Canon registries. Two passes:
// 1. foldRetiredCharactersBucket — Phase A retirement contract. ALWAYS
diff --git a/server/services/universeBuilder/store.js b/server/services/universeBuilder/store.js
index dc816c7b4c..11f4fe4737 100644
--- a/server/services/universeBuilder/store.js
+++ b/server/services/universeBuilder/store.js
@@ -101,6 +101,24 @@ function makeFileBackend(dir) {
const records = await listRaw();
return includeDeleted ? records.length : records.filter((r) => r?.deleted !== true).length;
},
+ // The file layout can't actually project — `deleted` and the style fields
+ // both live inside each record, so knowing which rows are live means
+ // reading them all (same constraint as countUniverses above). The `.map`
+ // is shape parity with db.listStyles, not a saving: both backends must
+ // hand the service the same row keys. Unordered — the service sorts.
+ listStyles: async () => {
+ const records = await listRaw();
+ return records
+ .filter((r) => r && r.deleted !== true)
+ .map((r) => ({
+ id: r.id,
+ name: r.name,
+ influences: r.influences,
+ stylePrompt: r.stylePrompt,
+ negativePrompt: r.negativePrompt,
+ createdAt: r.createdAt,
+ }));
+ },
writeRaw: (id, record) => cs.saveOneNow(id, record),
deleteRaw: (id) => cs.deleteOneNow(id),
loadRuns: async (universeId = null) => {
@@ -139,6 +157,7 @@ function makePgBackend(db) {
listIds: db.listIds,
listRaw: db.listRaw,
countUniverses: db.countUniverses,
+ listStyles: db.listStyles,
writeRaw: db.writeRaw,
deleteRaw: db.deleteRaw,
loadRuns: db.loadRuns,
@@ -196,6 +215,7 @@ function createFacade({ dir, sanitizeRecord }) {
listIds: async () => (await getBackend()).listIds(),
listRaw: async () => (await getBackend()).listRaw(),
countUniverses: async (opts) => (await getBackend()).countUniverses(opts),
+ listStyles: async () => (await getBackend()).listStyles(),
loadOneRaw: async (id) => (await getBackend()).readRaw(id),
loadOne: async (id) => {
const raw = await (await getBackend()).readRaw(id);
diff --git a/server/services/universeBuilder/store.test.js b/server/services/universeBuilder/store.test.js
index 4bb97e55ac..5b4a15439f 100644
--- a/server/services/universeBuilder/store.test.js
+++ b/server/services/universeBuilder/store.test.js
@@ -59,6 +59,25 @@ describe('universe store facade — file backend', () => {
expect(all.every((r) => !('_sanitized' in r))).toBe(true); // raw, not sanitized
});
+ it('listStyles projects to the style fields and drops tombstones', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ await s.writeRecord('u-1', {
+ id: 'u-1', name: 'A', logline: 'nope', createdAt: '2026-01-01T00:00:00.000Z',
+ influences: { embrace: ['ink'], avoid: [] },
+ });
+ await s.writeRecord('u-2', { id: 'u-2', name: 'B', deleted: true });
+ // Same row keys db.listStyles returns — the service derives tokens from
+ // them, so the two backends must hand it the identical shape.
+ expect(await s.listStyles()).toEqual([{
+ id: 'u-1',
+ name: 'A',
+ influences: { embrace: ['ink'], avoid: [] },
+ stylePrompt: undefined,
+ negativePrompt: undefined,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ }]);
+ });
+
it('deleteRecord removes the record', async () => {
const s = getUniverseStore(passthroughSanitize);
await s.writeRecord('u-1', { id: 'u-1', name: 'X' });
diff --git a/server/services/universeBuilder/storeFacade.js b/server/services/universeBuilder/storeFacade.js
index 5e3e0d9125..bf34077805 100644
--- a/server/services/universeBuilder/storeFacade.js
+++ b/server/services/universeBuilder/storeFacade.js
@@ -8,7 +8,7 @@
* `sanitizeTemplate` on read — and defers backend selection into each method, so
* this service keeps calling `store()` exactly as it did the collectionStore.
* Methods used here: loadOne / loadOneRaw / listIds / listRaw / countUniverses /
- * queueRecordWrite / writeRecord(id, rec) / deleteRecord(id) / loadRuns /
+ * listStyles / queueRecordWrite / writeRecord(id, rec) / deleteRecord(id) / loadRuns /
* appendRun / removeRunsForUniverses. `writeRecord`/`deleteRecord` replace the inline
* ensureDir+atomicWrite(recordPath) / rm(recordDir) the file layout used, and
* bump the mutation epoch so dataSync re-sends the universe snapshot to peers