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: configure creative commissions with a universe or mood board style source

[._.]/ Adam Eivyc3e8e0987812
diff --git a/client/src/components/creative-commission/CommissionConfigForm.jsx b/client/src/components/creative-commission/CommissionConfigForm.jsx
index 0b82b29da9..c906907baf 100644
--- a/client/src/components/creative-commission/CommissionConfigForm.jsx
+++ b/client/src/components/creative-commission/CommissionConfigForm.jsx
@@ -14,14 +14,17 @@
import { useEffect, useMemo, useState } from 'react';
import ProviderModelSelector from '../ProviderModelSelector';
import { isProcessProvider } from '../../utils/providers';
-import { getProviders, getSettings, listImageModels, listVideoModels, listMusicEngines } from '../../services/api';
+import {
+ getProviders, getSettings, listImageModels, listVideoModels, listMusicEngines,
+ listMoodBoardNames, listUniverseNames, listUniverseStyles,
+} from '../../services/api';
import { deriveAvailableBackends } from '../../lib/imageGenBackends';
import CronSchedulePicker from '../CronSchedulePicker';
import useUserTimezone from '../../hooks/useUserTimezone.js';
import {
inputCls, labelCls,
ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, mergeGenerationForAbility,
- backendFieldsForAbility, RENDER_BACKEND_AUTO,
+ backendFieldsForAbility, RENDER_BACKEND_AUTO, BOARD_FOLLOW_UNIVERSE, BOARD_NONE,
COMMISSION_NAME_MAX, COMMISSION_INTENT_MAX, COMMISSION_STYLE_SPEC_MAX, COMMISSION_BRIEF_TAG_MAX,
} from './commissionForm.js';
@@ -132,6 +135,9 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,
</div>
</section>
+ {/* Style source — a universe / mood board as the art-direction base */}
+ <StyleSourceSection styleSource={form.styleSource} patchForm={patchForm} />
+
{/* Schedule */}
<section className="space-y-3 border-t border-port-border pt-4">
<h3 className="text-sm font-semibold text-gray-200">Schedule</h3>
@@ -203,6 +209,104 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,
);
}
+// The universe and/or mood board a commission draws its look from — the same
+// pickers Code Animation offers. Each run resolves them fresh on the server
+// (services/creativeCommissions/styleSource.js): the universe's style tags,
+// notes, and style images plus the board's through-line and pins become the
+// art-direction base the Creative Director works from; the Style notes above
+// refine it.
+function StyleSourceSection({ styleSource, patchForm }) {
+ const [universes, setUniverses] = useState([]);
+ const [universeStyles, setUniverseStyles] = useState({});
+ const [boards, setBoards] = useState([]);
+
+ useEffect(() => {
+ let cancelled = false;
+ listUniverseNames({ silent: true })
+ .then((rows) => { if (!cancelled) setUniverses(Array.isArray(rows) ? rows : []); })
+ .catch(() => {});
+ listUniverseStyles({ silent: true })
+ .then((rows) => {
+ if (!cancelled) setUniverseStyles(Object.fromEntries((Array.isArray(rows) ? rows : []).map((row) => [row.id, row])));
+ })
+ .catch(() => {});
+ listMoodBoardNames({ silent: true })
+ .then((rows) => { if (!cancelled) setBoards(Array.isArray(rows) ? rows : []); })
+ .catch(() => {});
+ return () => { cancelled = true; };
+ }, []);
+
+ const { universeId, moodBoardChoice } = styleSource;
+ const activeStyle = universeId ? universeStyles[universeId] : null;
+ const embrace = activeStyle?.influences?.embrace || [];
+ const avoid = activeStyle?.influences?.avoid || [];
+ // Keep a stored choice selectable even before the lists load (or after the
+ // record it names was deleted), so the select never silently shows another value.
+ const universeKnown = !universeId || universes.some((u) => u.id === universeId);
+ const boardKnown = moodBoardChoice === BOARD_FOLLOW_UNIVERSE || moodBoardChoice === BOARD_NONE
+ || boards.some((b) => b.id === moodBoardChoice);
+
+ return (
+ <section className="space-y-3 border-t border-port-border pt-4">
+ <h3 className="text-sm font-semibold text-gray-200">Style source</h3>
+ <p className="text-xs text-gray-500">
+ Pick a universe or mood board and each run loads its style tags and reference images as the
+ Creative Director&apos;s art-direction base. Style notes above refine it.
+ </p>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div>
+ <label className={labelCls} htmlFor="commission-universe">Universe</label>
+ <select
+ id="commission-universe"
+ className={inputCls}
+ value={universeId}
+ onChange={(e) => patchForm(['styleSource', 'universeId'], e.target.value)}
+ >
+ <option value="">No universe</option>
+ {!universeKnown && <option value={universeId}>{universeId}</option>}
+ {universes.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
+ </select>
+ </div>
+ <div>
+ <label className={labelCls} htmlFor="commission-mood-board">Mood board</label>
+ <select
+ id="commission-mood-board"
+ className={inputCls}
+ value={moodBoardChoice}
+ onChange={(e) => patchForm(['styleSource', 'moodBoardChoice'], e.target.value)}
+ >
+ <option value={BOARD_FOLLOW_UNIVERSE}>Universe&apos;s linked board</option>
+ <option value={BOARD_NONE}>No mood board</option>
+ {!boardKnown && <option value={moodBoardChoice}>{moodBoardChoice}</option>}
+ {boards.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
+ </select>
+ </div>
+ </div>
+ {(embrace.length > 0 || avoid.length > 0) && (
+ <div className="flex flex-wrap gap-1 text-[11px]" aria-label="Universe style tags">
+ {embrace.slice(0, 12).map((token) => (
+ <span key={`e-${token}`} className="rounded bg-port-accent/15 px-1.5 py-0.5 text-port-accent">{token}</span>
+ ))}
+ {avoid.slice(0, 6).map((token) => (
+ <span key={`a-${token}`} className="rounded bg-port-error/15 px-1.5 py-0.5 text-port-error line-through">{token}</span>
+ ))}
+ </div>
+ )}
+ {universeId && universeKnown && universes.length > 0 && !activeStyle && (
+ <p className="text-xs text-gray-500">
+ This universe has no style tags yet — only its notes, style references, and images will be used.{' '}
+ <a href={`/universes/${encodeURIComponent(universeId)}`} className="text-port-accent hover:underline">Edit its style guide</a>
+ </p>
+ )}
+ {boards.length === 0 && (
+ <p className="text-xs text-gray-500">
+ No mood boards yet. <a href="/mood-boards" className="text-port-accent hover:underline">Create a mood board</a> to collect style references.
+ </p>
+ )}
+ </section>
+ );
+}
+
// Generation params for the selected output type (#2769). Renders the ability's
// field descriptors (GENERATION_FIELDS_BY_ABILITY) generically so all five types
// share one layout — a select for enum fields, a bounded number input otherwise.
diff --git a/client/src/components/creative-commission/CommissionConfigForm.test.jsx b/client/src/components/creative-commission/CommissionConfigForm.test.jsx
index 31cfd7ff87..b3a13b3805 100644
--- a/client/src/components/creative-commission/CommissionConfigForm.test.jsx
+++ b/client/src/components/creative-commission/CommissionConfigForm.test.jsx
@@ -7,6 +7,7 @@ import { patchFormState, toForm } from './commissionForm.js';
const api = vi.hoisted(() => ({
listMusicEngines: vi.fn(), getProviders: vi.fn(), getSettings: vi.fn(),
listImageModels: vi.fn(), listVideoModels: vi.fn(),
+ listUniverseNames: vi.fn(), listUniverseStyles: vi.fn(), listMoodBoardNames: vi.fn(),
}));
vi.mock('../../services/api', () => api);
vi.mock('../../services/apiLocalLlm', () => ({ getToolUseModels: vi.fn(async () => ({ providers: [] })) }));
@@ -37,6 +38,9 @@ beforeEach(() => {
api.getSettings.mockResolvedValue({});
api.listImageModels.mockResolvedValue([]);
api.listVideoModels.mockResolvedValue([]);
+ api.listUniverseNames.mockResolvedValue([]);
+ api.listUniverseStyles.mockResolvedValue([]);
+ api.listMoodBoardNames.mockResolvedValue([]);
api.listMusicEngines.mockResolvedValue({
defaultEngine: 'musicgen',
engines: [{
@@ -106,6 +110,34 @@ describe('CommissionConfigForm music taste controls', () => {
});
});
+describe('CommissionConfigForm style source', () => {
+ it('picks a universe, previews its style tags, and picks a mood board', async () => {
+ api.listUniverseNames.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);
+ api.listUniverseStyles.mockResolvedValue([{ id: 'u1', name: 'Example Universe', influences: { embrace: ['ink wash'], avoid: ['neon'] } }]);
+ api.listMoodBoardNames.mockResolvedValue([{ id: 'b1', name: 'Example Board' }]);
+ let latest;
+ function StyleHarness() {
+ const [form, setForm] = useState(toForm({ brief: { intent: 'a drifting city' } }));
+ latest = form;
+ return (
+ <CommissionConfigForm
+ form={form}
+ patchForm={(path, value) => setForm((prev) => patchFormState(prev, path, value))}
+ saving={false}
+ onSave={() => {}}
+ />
+ );
+ }
+ render(<StyleHarness />);
+ await waitFor(() => expect(screen.getByLabelText('Universe')).toContainHTML('Example Universe'));
+ fireEvent.change(screen.getByLabelText('Universe'), { target: { value: 'u1' } });
+ expect(await screen.findByText('ink wash')).toBeInTheDocument();
+ expect(screen.getByText('neon')).toBeInTheDocument();
+ fireEvent.change(screen.getByLabelText('Mood board'), { target: { value: 'b1' } });
+ expect(latest.styleSource).toEqual({ universeId: 'u1', moodBoardChoice: 'b1' });
+ });
+});
+
describe('CommissionConfigForm video duration controls', () => {
it('defaults to Creative Director choice and reveals a manual length when selected', async () => {
function VideoHarness() {
diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.js
index 51ab06c2b9..ac208cb417 100644
--- a/client/src/components/creative-commission/commissionForm.js
+++ b/client/src/components/creative-commission/commissionForm.js
@@ -231,6 +231,23 @@ export function generationToPayload(ability, generation) {
return out;
}
+// Mood-board choice sentinels for the style-source picker (form-only values —
+// never real board ids). The wire contract is the server's
+// (services/creativeCommissions/styleSource.js): a null moodBoardId follows the
+// universe's linked board, '' means no board, any other string names one.
+export const BOARD_FOLLOW_UNIVERSE = '__universe__';
+export const BOARD_NONE = '__none__';
+
+function boardChoiceFromRecord(moodBoardId) {
+ if (moodBoardId == null) return BOARD_FOLLOW_UNIVERSE;
+ return moodBoardId === '' ? BOARD_NONE : moodBoardId;
+}
+
+function boardIdFromChoice(choice) {
+ if (choice === BOARD_FOLLOW_UNIVERSE) return null;
+ return choice === BOARD_NONE ? '' : choice;
+}
+
// Human-readable cadence summary for the list card + detail header.
export function describeSchedule(schedule) {
if (!schedule) return 'No schedule';
@@ -261,6 +278,12 @@ export function toForm(c) {
genre: c.brief?.genre || '',
styleSpec: c.brief?.styleSpec || '',
},
+ // The universe / mood board whose style tags and reference images are the
+ // art-direction base each run hands the Creative Director.
+ styleSource: {
+ universeId: c.brief?.constraints?.universeId || '',
+ moodBoardChoice: boardChoiceFromRecord(c.brief?.constraints?.moodBoardId),
+ },
musicTaste: c.brief?.musicTaste ? {
enabled: true,
source: 'digital-twin',
@@ -334,6 +357,11 @@ export function toPayload(form) {
intent: form.brief.intent.trim(),
genre: form.brief.genre.trim() || null,
styleSpec: form.brief.styleSpec,
+ // Merged one level deep server-side, so a stored seriesId survives.
+ constraints: {
+ universeId: form.styleSource.universeId || null,
+ moodBoardId: boardIdFromChoice(form.styleSource.moodBoardChoice),
+ },
musicTaste: form.targetAbility === 'music' && form.musicTaste.enabled ? {
source: 'digital-twin',
window: form.musicTaste.window,
diff --git a/client/src/components/creative-commission/commissionForm.test.js b/client/src/components/creative-commission/commissionForm.test.js
index 372a8b864a..b2d0594856 100644
--- a/client/src/components/creative-commission/commissionForm.test.js
+++ b/client/src/components/creative-commission/commissionForm.test.js
@@ -4,7 +4,7 @@ import {
describeSchedule, describeAssignment,
ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, GENERATION_DEFAULTS_BY_ABILITY,
generationToForm, mergeGenerationForAbility, generationToPayload,
- backendFieldsForAbility, RENDER_BACKEND_AUTO,
+ backendFieldsForAbility, RENDER_BACKEND_AUTO, BOARD_FOLLOW_UNIVERSE, BOARD_NONE,
IMAGE_BACKEND_OPTIONS, VIDEO_BACKEND_OPTIONS,
} from './commissionForm.js';
@@ -74,6 +74,23 @@ describe('commissionForm helpers', () => {
expect(toPayload(form).brief.genre).toBeNull();
});
+ // The board picker's three choices map onto the server's wire contract
+ // (styleSource.js): null follows the universe's board, '' is none, an id is
+ // explicit. A wrong mapping silently swaps which look every run uses.
+ it('round-trips the universe / mood-board style source through the wire contract', () => {
+ const follow = toForm({ id: 'c1', brief: { intent: 'x', constraints: { universeId: 'u1' } } });
+ expect(follow.styleSource).toEqual({ universeId: 'u1', moodBoardChoice: BOARD_FOLLOW_UNIVERSE });
+ expect(toPayload({ ...follow, name: 'n' }).brief.constraints).toEqual({ universeId: 'u1', moodBoardId: null });
+
+ const none = toForm({ id: 'c1', brief: { intent: 'x', constraints: { universeId: 'u1', moodBoardId: '' } } });
+ expect(none.styleSource.moodBoardChoice).toBe(BOARD_NONE);
+ expect(toPayload({ ...none, name: 'n' }).brief.constraints.moodBoardId).toBe('');
+
+ const explicit = toForm({ id: 'c1', brief: { intent: 'x', constraints: { moodBoardId: 'b1' } } });
+ expect(explicit.styleSource).toEqual({ universeId: '', moodBoardChoice: 'b1' });
+ expect(toPayload({ ...explicit, name: 'n' }).brief.constraints).toEqual({ universeId: null, moodBoardId: 'b1' });
+ });
+
it('round-trips taste controls only for an opted-in music commission', () => {
const form = toForm({
name: 'Taste study', targetAbility: 'music', brief: {
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index f423bb04e4..5009946778 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -109,7 +109,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,
| **Rounds & Rounds Guide** | `/rounds`, `/rounds/guide` | Composition and learning tool for a cappella musical rounds, multi-part vocal harmonies, lead sheets, and solfège notation. | — |
| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — |
| **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — |
-| **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. | — |
+| **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base. | — |
| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, and tempo alignment. | — |
| **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |
diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.js
index f63541fffd..72ed1a8146 100644
--- a/server/lib/creativeCommissionValidation.js
+++ b/server/lib/creativeCommissionValidation.js
@@ -103,6 +103,18 @@ export const creativeCommissionMusicTasteUpdateSchema = z.object({
musicModelId: musicTasteEngineId,
}).nullable();
+// Scope + style source. `universeId` scopes a series AND supplies the style
+// base (its style guide + images); `moodBoardId` picks the board whose
+// through-line and pins join that base — absent/null follows the universe's
+// linked board, '' means none, any other string names a board (see
+// services/creativeCommissions/styleSource.js). No defaults, so the PATCH
+// path's one-level-deeper merge preserves an omitted key.
+const commissionConstraintsSchema = z.object({
+ universeId: z.string().max(120).nullable().optional(),
+ seriesId: z.string().max(120).nullable().optional(),
+ moodBoardId: z.string().max(120).nullable().optional(),
+});
+
// The brief the commission steers by. `intent` is the free-text core ("something
// surreal, dreamlike, unsettlingly beautiful"); `genre`/`category` are optional
// lightweight tags (a real taxonomy arrives in Phase 5); `styleSpec` maps to the
@@ -112,10 +124,7 @@ export const creativeCommissionBriefSchema = z.object({
genre: z.string().trim().max(COMMISSION_BRIEF_TAG_MAX).nullable().optional(),
category: z.string().trim().max(COMMISSION_BRIEF_TAG_MAX).nullable().optional(),
styleSpec: z.string().max(COMMISSION_STYLE_SPEC_MAX).default(''),
- constraints: z.object({
- universeId: z.string().max(120).nullable().optional(),
- seriesId: z.string().max(120).nullable().optional(),
- }).default({}),
+ constraints: commissionConstraintsSchema.default({}),
// Catalog ingredient ids to seed future generations from (Phase 3+ folds these
// into the CD cast). Accepted now so the record shape is forward-stable.
seedRefs: z.array(z.string().trim().max(64)).max(50).default([]),
@@ -277,10 +286,7 @@ export const creativeCommissionBriefUpdateSchema = z.object({
genre: z.string().trim().max(COMMISSION_BRIEF_TAG_MAX).nullable().optional(),
category: z.string().trim().max(COMMISSION_BRIEF_TAG_MAX).nullable().optional(),
styleSpec: z.string().max(COMMISSION_STYLE_SPEC_MAX).optional(),
- constraints: z.object({
- universeId: z.string().max(120).nullable().optional(),
- seriesId: z.string().max(120).nullable().optional(),
- }).optional(),
+ constraints: commissionConstraintsSchema.optional(),
seedRefs: z.array(z.string().trim().max(64)).max(50).optional(),
musicTaste: creativeCommissionMusicTasteUpdateSchema.optional(),
});
diff --git a/server/services/README.md b/server/services/README.md
index c69c364bf6..e818a2bd42 100644
--- a/server/services/README.md
+++ b/server/services/README.md
@@ -10,6 +10,7 @@ image-generation paths below are useful entry points when tracing render jobs.
| `imageGen/index.js` | Mode-aware image backend dispatcher and shared image-generation helpers. Direct queue consumers still resolve local model identity before enqueueing. |
| `universeBuilderRender.js` | Universe Builder batch render jobs. |
| `pipeline/visualStageHelpers.js` | Shared pipeline visual prompt, LoRA compatibility, and image-job enqueue helpers. |
+| `creativeStyleSources.js` | Resolves a universe style guide or mood board into art-direction text plus local reference images; shared by Code Animation and Creative Commissions. |
| `creativeDirector/firstPassGen.js` | Gracefully gated first-pass portraits and scene frames. |
| `universeCharacterSheet.js` | Character reference-sheet render and completion workflow. |
| `loraDatasetGenerate.js` | Training-image render and dataset lifecycle. |
diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.js
index 79a62e246a..d36879b690 100644
--- a/server/services/codeAnimation/index.js
+++ b/server/services/codeAnimation/index.js
@@ -16,12 +16,12 @@ import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { emitCodeAnimationChanged } from '../socket.js';
import { PATHS } from '../../lib/paths.js';
-import { makePathResolver, resolveGalleryImage, resolveImageRef } from '../../lib/pathSafety.js';
-import { universeVisualStyleTokens } from '../../lib/universeVisualStyle.js';
+import { makePathResolver } from '../../lib/pathSafety.js';
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
import { UPLOAD_AUDIO_EXTENSIONS } from '../../lib/mimeTypes.js';
import { normalizeWaveSketch } from '../../lib/waveSketch.js';
import { SUPPORTED_AUDIO_EXTENSIONS } from '../pipeline/musicLibrary.js';
+import { resolveMoodBoardStyleSource as resolveMoodBoard, resolveUniverseStyleSource as resolveUniverse } from '../creativeStyleSources.js';
import {
getCodeAnimationJobRecord,
isCodeAnimationJobId,
@@ -67,97 +67,6 @@ export function getCodeAnimationOptions() {
};
}
-// The two served image dirs a reference can live in, by asset kind.
-const IMAGE_DIRS = {
- 'image-ref': { resolve: resolveImageRef, urlPrefix: '/data/image-refs/' },
- image: { resolve: resolveGalleryImage, urlPrefix: '/data/images/' },
-};
-
-// A local image as a prompt reference, or null when the file is missing.
-function localReference(kind, filename, label, origin) {
- const dir = IMAGE_DIRS[kind];
- const path = dir?.resolve(filename);
- return path ? { label, origin, path, url: `${dir.urlPrefix}${encodeURIComponent(filename)}` } : null;
-}
-
-// Resolve reference candidates in order until `slots` are filled, so a
-// universe or board with many images costs only the stats it can use.
-function fillReferences(candidates, slots) {
- const images = [];
- for (const candidate of candidates) {
- if (images.length >= slots) break;
- const image = candidate();
- if (image && !images.some((existing) => existing.path === image.path)) images.push(image);
- }
- return images;
-}
-
-// The narrative half of a universe — its bible text and canon arrays, passed
-// through for `renderCanonForPrompt` to project. Only the brief writer reads
-// it: the coding prompt is art direction, and a logline or a character's
-// motivations would just crowd out the runtime contract.
-function universeNarrative(universe) {
- const { characters, places, objects } = universe;
- return {
- logline: trimTo(universe.logline, 2_000),
- premise: trimTo(universe.premise, 4_000),
- characters,
- places,
- objects,
- };
-}
-
-async function resolveUniverse(universeId, { imageSlots, narrative = false }) {
- if (!universeId) return null;
- const { getUniverse } = await import('../universeBuilder/crud.js');
- const universe = await getUniverse(universeId).catch((error) => {
- if (error?.code === 'NOT_FOUND') throw new ServerError('Universe not found', { status: 404, code: 'NOT_FOUND' });
- throw error;
- });
- const { embrace, avoid } = universeVisualStyleTokens(universe);
- const refs = Array.isArray(universe.styleReferences) ? universe.styleReferences : [];
- const styleReferences = refs
- .filter((ref) => isNonBlankStr(ref?.prompt))
- .slice(0, 6)
- .map((ref) => ({ title: trimTo(ref.title, 120), prompt: trimTo(ref.prompt, 600) }));
- // A style image lives in either served dir depending on how it was made
- // (style-reference upload vs gallery probe), so try refs first, then gallery.
- const styleImage = (filename, label) => () => localReference('image-ref', filename, label, 'universe')
- || localReference('image', filename, label, 'universe');
- const candidates = [
- ...refs.map((ref) => [ref?.imageRefs?.[0], trimTo(ref?.title, 120) || 'Universe style reference']),
- ...(Array.isArray(universe.styleImageRefs) ? universe.styleImageRefs : []).map((filename) => [filename, 'Universe style probe']),
- ].filter(([filename]) => isNonBlankStr(filename)).map(([filename, label]) => styleImage(filename, label));
- const images = fillReferences(candidates, imageSlots);
- return {
- name: universe.name,
- embrace,
- avoid,
- styleNotes: trimTo(universe.styleNotes, 2_000),
- styleReferences,
- moodBoardId: isNonBlankStr(universe.moodBoardId) ? universe.moodBoardId : null,
- images,
- ...(narrative ? universeNarrative(universe) : {}),
- };
-}
-
-async function resolveMoodBoard(moodBoardId, { imageSlots }) {
- if (!moodBoardId) return { board: null, images: [] };
- const [{ getBoard }, { collectBoardStyleContext }, { boardItemLocalImage }] = await Promise.all([
- import('../moodBoard/db.js'),
- import('../moodBoard/styleContext.js'),
- import('../moodBoard/logic.js'),
- ]);
- const board = await getBoard(moodBoardId);
- if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
- // Text items, videos, and external pins attach nothing — they still
- // contribute their caption/analysis text through the board context.
- const candidates = (board.items || []).map((item) => () => {
- const asset = boardItemLocalImage(item);
- return asset ? localReference(asset.kind, asset.filename, trimTo(item.caption, 120) || asset.filename, 'mood-board') : null;
- });
- return { board: collectBoardStyleContext(board), images: fillReferences(candidates, imageSlots) };
-}
function resolveUploadedImages(referenceImages) {
return referenceImages.map((ref) => {
diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.js
index 4fabf016a6..e99db0a638 100644
--- a/server/services/creativeCommissions/abilityAdapters.js
+++ b/server/services/creativeCommissions/abilityAdapters.js
@@ -90,12 +90,15 @@ function sanitizeGenerationFor(ability, raw) {
// Build the common brief lines (intent + genre/category/style) shared by every
// adapter's directive, with a type-specific lead sentence prepended by the
// caller. Returns { lines, digest, constraints } — the adapter assembles the goal
-// via composeDirectiveGoal.
-function briefContext(commission, leadSentence) {
+// via composeDirectiveGoal. `styleSource` is the fire-time resolution of the
+// commission's universe / mood board (styleSource.js): its text is the art
+// direction BASE, so it precedes the user's own style notes, which refine it.
+function briefContext(commission, leadSentence, { styleSource } = {}) {
const brief = commission?.brief || {};
const lines = [`${leadSentence} ${String(brief.intent || '').trim()}`.trim()];
if (brief.genre) lines.push(`Genre: ${brief.genre}.`);
if (brief.category) lines.push(`Category: ${brief.category}.`);
+ if (styleSource?.text) lines.push(styleSource.text);
if (brief.styleSpec) lines.push(`Style: ${brief.styleSpec}.`);
const digest = renderFeedbackDigest(commission?.feedback, commission?.feedbackWindow ?? 5);
// Preserve the user's structured form choices alongside the prose brief.
@@ -111,6 +114,9 @@ function briefContext(commission, leadSentence) {
};
if (brief.constraints?.universeId) constraints.universeId = brief.constraints.universeId;
if (brief.constraints?.seriesId) constraints.seriesId = brief.constraints.seriesId;
+ // The RESOLVED board (an explicit pick, or the universe's linked one) — the
+ // stored choice may be the follow-the-universe sentinel.
+ if (styleSource?.moodBoardId) constraints.moodBoardId = styleSource.moodBoardId;
return { lines, digest, constraints };
}
@@ -212,10 +218,11 @@ const videoAdapter = {
label: 'Video',
sanitizeGeneration: (raw) => sanitizeGenerationFor('video', raw),
buildProjectParams: buildVideoGeometryParams,
- buildDirective(commission, { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId } = {}) {
+ buildDirective(commission, options = {}) {
+ const { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId } = options;
const duration = isAutoDuration(commission?.generation)
? ' Choose an appropriate duration between 5 and 600 seconds for the brief.' : '';
- const { lines, digest, constraints } = briefContext(commission, `Create a short-form video piece.${duration}`);
+ const { lines, digest, constraints } = briefContext(commission, `Create a short-form video piece.${duration}`, options);
lines.unshift(videoPromptGuidanceFor(commission, { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId }));
return { goal: composeDirectiveGoal(lines, digest), deliverables: ['One rendered video matching the brief'], constraints };
},
@@ -226,11 +233,11 @@ const imageAdapter = {
label: 'Image',
sanitizeGeneration: (raw) => sanitizeGenerationFor('image', raw),
buildProjectParams: buildVideoGeometryParams,
- buildDirective(commission) {
+ buildDirective(commission, options = {}) {
const count = genValue(commission, 'imageCount');
const noun = count === 1 ? 'a single still image' : `${count} still images`;
const lead = `Produce ${noun}. Use the image / catalog generation tools; do NOT plan a video or music render.`;
- const { lines, digest, constraints } = briefContext(commission, lead);
+ const { lines, digest, constraints } = briefContext(commission, lead, options);
return {
goal: composeDirectiveGoal(lines, digest),
deliverables: [count === 1 ? 'One still image matching the brief' : `${count} still images matching the brief`],
@@ -244,10 +251,11 @@ const musicAdapter = {
label: 'Music',
sanitizeGeneration: (raw) => sanitizeGenerationFor('music', raw),
buildProjectParams: buildVideoGeometryParams,
- buildDirective(commission, { tasteRecipe } = {}) {
+ buildDirective(commission, options = {}) {
+ const { tasteRecipe } = options;
const secs = genValue(commission, 'lengthSeconds');
const lead = `Compose an original ~${secs}s music / audio piece. Use the music generation tools; do NOT plan a video or image render.`;
- const { lines, digest, constraints } = briefContext(commission, lead);
+ const { lines, digest, constraints } = briefContext(commission, lead, options);
const tastePrompt = renderMusicTasteRecipePrompt(tasteRecipe);
// Keep the bounded recipe + original-work constraint ahead of the optional
// brief tags (genre / category / style). composeDirectiveGoal truncates only
@@ -263,11 +271,12 @@ const musicVideoAdapter = {
label: 'Music video',
sanitizeGeneration: (raw) => sanitizeGenerationFor('music-video', raw),
buildProjectParams: buildVideoGeometryParams,
- buildDirective(commission, { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId } = {}) {
+ buildDirective(commission, options = {}) {
+ const { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId } = options;
const duration = isAutoDuration(commission?.generation)
? ' Choose an appropriate video duration between 5 and 600 seconds for the brief.' : '';
const lead = `Create a short-form music video:${duration} Generate an original music bed AND a matching video scored to it.`;
- const { lines, digest, constraints } = briefContext(commission, lead);
+ const { lines, digest, constraints } = briefContext(commission, lead, options);
lines.unshift(videoPromptGuidanceFor(commission, { defaultVideoModelId, effectiveVideoMode, effectiveVideoModelId }));
return {
goal: composeDirectiveGoal(lines, digest),
@@ -282,7 +291,7 @@ const seriesAdapter = {
label: 'Series',
sanitizeGeneration: (raw) => sanitizeGenerationFor('series', raw),
buildProjectParams: buildVideoGeometryParams,
- buildDirective(commission) {
+ buildDirective(commission, options = {}) {
const count = genValue(commission, 'episodeCount');
const hasUniverse = !!commission?.brief?.constraints?.universeId;
const scope = hasUniverse
@@ -290,7 +299,7 @@ const seriesAdapter = {
: 'Invent a fitting universe context for the series.';
const noun = count === 1 ? 'its opening issue/episode' : `its first ${count} issues/episodes`;
const lead = `Create a new episodic series and generate ${noun}. ${scope} Use the pipeline series tools.`;
- const { lines, digest, constraints } = briefContext(commission, lead);
+ const { lines, digest, constraints } = briefContext(commission, lead, options);
return {
goal: composeDirectiveGoal(lines, digest),
deliverables: [count === 1 ? 'A new series with its opening issue/episode started' : `A new series with its first ${count} issues/episodes started`],
diff --git a/server/services/creativeCommissions/abilityAdapters.test.js b/server/services/creativeCommissions/abilityAdapters.test.js
index 5cc5b40d53..5bf66214f4 100644
--- a/server/services/creativeCommissions/abilityAdapters.test.js
+++ b/server/services/creativeCommissions/abilityAdapters.test.js
@@ -6,7 +6,7 @@ import { CREATIVE_COMMISSION_ABILITIES, ABILITY_GENERATION_SPEC } from '../../li
import {
COMMISSION_INTENT_MAX, COMMISSION_STYLE_SPEC_MAX, COMMISSION_BRIEF_TAG_MAX,
} from '../../lib/creativeBriefLimits.js';
-import { MAX_DIRECTIVE_GOAL_LEN } from './directive.js';
+import { MAX_DIRECTIVE_GOAL_LEN, MAX_STYLE_SOURCE_LEN } from './directive.js';
import { buildVideoPromptGuidance, isMiniMaxVideoModel } from './videoPromptGuidance.js';
const MAXED_INTENT = 'x'.repeat(COMMISSION_INTENT_MAX);
@@ -103,19 +103,34 @@ describe('buildCommissionDirective — video (unchanged brief/feedback fold)', (
// store, so the system prefix AND the user's own words must both survive it:
// the clamp drops the tail, and the guidance is prepended, so an under-sized
// MAX_DIRECTIVE_GOAL_LEN would silently eat the brief instead of erroring.
- it('carries a brief filled to the schema caps AND the MiniMax recipe', () => {
+ it('carries a brief filled to the schema caps, a maxed style source, AND the MiniMax recipe', () => {
const intent = 'x'.repeat(COMMISSION_INTENT_MAX);
const styleSpec = 'y'.repeat(COMMISSION_STYLE_SPEC_MAX);
+ const styleSource = { text: 's'.repeat(MAX_STYLE_SOURCE_LEN), moodBoardId: 'b1' };
const directive = buildCommissionDirective({
targetAbility: 'video',
brief: { intent, styleSpec, genre: 'g'.repeat(COMMISSION_BRIEF_TAG_MAX), category: 'c'.repeat(COMMISSION_BRIEF_TAG_MAX) },
feedback: Array.from({ length: 50 }, (_, i) => ({ rating: i % 2 === 0 ? 'up' : 'down', note: 'z'.repeat(1000) })),
feedbackWindow: 50,
generation: { videoModelId: 'minimax_h3_cuda' },
- });
+ }, { styleSource });
expect(directive.goal).toContain('MiniMax H3 prompt template');
expect(directive.goal).toContain(intent);
expect(directive.goal).toContain(styleSpec);
+ expect(directive.goal).toContain(styleSource.text);
+ expect(directive.goal.length).toBeLessThanOrEqual(MAX_DIRECTIVE_GOAL_LEN);
+ });
+
+ // The universe / mood board base must reach EVERY output type's planner —
+ // the plan stage never renders the project styleSpec — ahead of the user's
+ // own style notes, with the resolved board id in the constraints.
+ it.each(['video', 'image', 'music', 'music-video', 'series'])('folds the style source into the %s directive', (targetAbility) => {
+ const directive = buildCommissionDirective(
+ { targetAbility, brief: { intent: 'a quiet harbor', styleSpec: 'flat color', constraints: { universeId: 'u1' } } },
+ { styleSource: { text: 'Art direction base: ink wash', moodBoardId: 'b1' } },
+ );
+ expect(directive.goal.indexOf('Art direction base: ink wash')).toBeLessThan(directive.goal.indexOf('Style: flat color'));
+ expect(directive.constraints).toMatchObject({ universeId: 'u1', moodBoardId: 'b1' });
});
it('uses the install default model when choosing model-specific guidance', () => {
diff --git a/server/services/creativeCommissions/directive.js b/server/services/creativeCommissions/directive.js
index 44d1813725..ef5c541de1 100644
--- a/server/services/creativeCommissions/directive.js
+++ b/server/services/creativeCommissions/directive.js
@@ -35,6 +35,10 @@ export const MAX_DIGEST_LEN = 1500;
// music taste recipe). Not derived — those strings are prose, not capped fields —
// so directive.test.js measures the real ones against this allowance.
export const MAX_SYSTEM_PREFIX_LEN = 3000;
+// The art-direction base a commission's universe / mood board contributes
+// (styleSource.js renders it at fire time). Bounded so the derived goal budget
+// below stays under CREATIVE_DIRECTOR_GOAL_MAX.
+export const MAX_STYLE_SOURCE_LEN = 2000;
// DERIVED, not tuned: the sum of every bounded part one goal can hold. The clamp
// drops the TAIL and the adapters put system text FIRST, so a budget short of
// this sum eats the user's own words rather than erroring — which is why raising
@@ -43,6 +47,7 @@ export const MAX_DIRECTIVE_GOAL_LEN = COMMISSION_INTENT_MAX
+ COMMISSION_STYLE_SPEC_MAX
+ (COMMISSION_BRIEF_TAG_MAX * 2) // genre + category
+ MAX_DIGEST_LEN
+ + MAX_STYLE_SOURCE_LEN
+ MAX_SYSTEM_PREFIX_LEN;
const clamp = (s, max) => (s.length > max ? `${s.slice(0, Math.max(0, max - 1))}…` : s);
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index e9139d6055..6a5547443f 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -440,10 +440,14 @@ async function fireCommission(commission, trigger) {
// the planner (routing it through dequeueNextTask instead of the direct
// task:ready emit shared with the CD directive flow) is the deeper CoS-queue
// gap tracked on #2657.
- const [{ createProject }, { advanceAfterPlanStepSettled }, { defaultVideoModelId }] = await Promise.all([
+ const [
+ { createProject }, { advanceAfterPlanStepSettled }, { defaultVideoModelId },
+ { composeCommissionStyleSpec, resolveCommissionStyleSource },
+ ] = await Promise.all([
import('../creativeDirector/local.js'),
import('../creativeDirector/planAdvance.js'),
import('../videoGen/local.js'),
+ import('./styleSource.js'),
]);
const settings = (commission.targetAbility === 'video' || commission.targetAbility === 'music-video')
@@ -457,7 +461,13 @@ async function fireCommission(commission, trigger) {
const effectiveVideoModelId = effectiveVideoMode === VIDEO_GEN_MODE.LOCAL
? renderTargetDefaults(settings, RENDER_TARGET.CREATIVE_AGENT).videoModel
: null;
+ // The configured universe / mood board is the art-direction base for both
+ // the planner (via the goal) and the treatment/evaluation stages (via the
+ // project styleSpec). Resolved per fire so edits to the universe or board
+ // reach the next run.
+ const styleSource = await resolveCommissionStyleSource(commission);
const directive = buildCommissionDirective(commission, {
+ styleSource,
tasteRecipe: startedTasteRecipe,
defaultVideoModelId,
effectiveVideoMode,
@@ -479,7 +489,7 @@ async function fireCommission(commission, trigger) {
const project = await createProject({
name: `${baseName}${dateSuffix}`,
...projectParams,
- styleSpec: commission.brief?.styleSpec || '',
+ styleSpec: composeCommissionStyleSpec(commission.brief?.styleSpec, styleSource),
directive,
// The back-pointer, NOT a copy of the commission's provider pin. agentBridge
// resolves that pin live from this id at every dispatch, so an edit to the
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index 4ad7a30d57..d6dba75d91 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -88,6 +88,11 @@ vi.mock('../domainUsage.js', () => ({
getDomainBudgetStatus: (...a) => budgetMock(...a),
recordDomainUsage: (...a) => recordUsageMock(...a),
}));
+const resolveUniverseStyleMock = vi.fn();
+vi.mock('../creativeStyleSources.js', () => ({
+ resolveUniverseStyleSource: (...a) => resolveUniverseStyleMock(...a),
+ resolveMoodBoardStyleSource: async () => ({ board: null, images: [] }),
+}));
const {
activeCommissions,
@@ -304,6 +309,20 @@ describe('runScheduledCommission gates', () => {
expect(getProviderByIdMock).not.toHaveBeenCalled();
});
+ it('hands the configured universe style to both the planner goal and the project styleSpec', async () => {
+ resolveUniverseStyleMock.mockResolvedValue({
+ name: 'Example Universe', embrace: ['ink wash'], avoid: [], styleNotes: '', styleReferences: [], moodBoardId: null, images: [],
+ });
+ getCommissionMock.mockResolvedValue(videoCommission({
+ brief: { intent: 'surreal', styleSpec: 'flat', constraints: { universeId: 'u1' } },
+ }));
+ await runScheduledCommission('commission-1');
+ const [params] = createProjectMock.mock.calls[0];
+ expect(params.directive.goal).toContain('Visual style to embrace: ink wash');
+ expect(params.styleSpec).toContain('Visual style to embrace: ink wash');
+ expect(params.styleSpec.endsWith('flat')).toBe(true);
+ });
+
it('does NOT surface when the fire is skipped (nothing was generated)', async () => {
creativeModeMock.mockReturnValue('off');
getCommissionMock.mockResolvedValue(videoCommission());
diff --git a/server/services/creativeCommissions/styleSource.js b/server/services/creativeCommissions/styleSource.js
new file mode 100644
index 0000000000..0adb64b1ad
--- /dev/null
+++ b/server/services/creativeCommissions/styleSource.js
@@ -0,0 +1,120 @@
+/**
+ * Creative Commission style source — the universe and/or mood board a
+ * commission is configured with, resolved at fire time into the art-direction
+ * BASE the Creative Director works from.
+ *
+ * The same pickers Card Decks and Code Animation offer: a universe contributes
+ * its style guide (embrace/avoid tokens, curated style references, style
+ * notes, style images) and, by default, its linked mood board; a mood board
+ * contributes its through-line (captions, notes, visual analyses) and pinned
+ * images. The rendered text is folded into both the directive goal (the
+ * planner never sees the project styleSpec) and the project's styleSpec (what
+ * the treatment and evaluation stages judge against). Reference images are
+ * listed by their served `/data/...` path — the same convention the treatment
+ * prompt uses for a starting image — never by an absolute machine path.
+ *
+ * Board selection on the stored brief (`brief.constraints.moodBoardId`):
+ * absent / null follows the universe's linked board, '' means no board, any
+ * other string names a board explicitly — matching Code Animation's wire
+ * contract, where an absent id follows the universe and '' means none.
+ */
+
+import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
+import { moodBoardSection, universeStyleLines } from '../codeAnimation/prompt.js';
+import { resolveMoodBoardStyleSource, resolveUniverseStyleSource } from '../creativeStyleSources.js';
+import { COMMISSION_STYLE_SPEC_MAX } from '../../lib/creativeBriefLimits.js';
+import { MAX_STYLE_SOURCE_LEN } from './directive.js';
+
+export const COMMISSION_STYLE_REFERENCE_IMAGES_MAX = 4;
+const IMAGE_LABEL_MAX = 60;
+const STYLE_SOURCE_HEADER = "Art direction base (from the commission's universe / mood board — ground every render in it):";
+
+const clamp = (s, max) => (s.length > max ? `${s.slice(0, Math.max(0, max - 1))}…` : s);
+
+// A universe or board deleted after the commission was configured must not
+// kill every future fire: skip it with a warning and render from what is left.
+// Any other failure (a DB outage) propagates — it is not evidence of deletion.
+async function orSkipMissing(label, promise, fallback) {
+ return promise.catch((error) => {
+ if (error?.code !== 'NOT_FOUND') throw error;
+ console.warn(`⚠️ Creative commission style source ${label} not found — firing without it`);
+ return fallback;
+ });
+}
+
+/**
+ * Render resolved style inputs into the bounded art-direction base. Pure.
+ * Returns '' when there is nothing to say.
+ */
+export function renderCommissionStyleSource({ universe = null, board = null, images = [] }) {
+ const sections = [];
+ if (universe) {
+ const lines = [`The look comes from the universe "${universe.name}" — match its established style so this work sits beside its other artwork.`];
+ lines.push(...universeStyleLines(universe));
+ if (isNonBlankStr(universe.styleNotes)) lines.push(`Tone and staging notes: ${universe.styleNotes}`);
+ sections.push(lines.join('\n'));
+ }
+ const boardText = moodBoardSection(board);
+ if (boardText) sections.push(boardText);
+ const imageLines = images.map((image, index) => {
+ const origin = image.origin === 'mood-board' ? 'mood board' : 'universe';
+ return `${index + 1}. ${trimTo(image.label, IMAGE_LABEL_MAX)} [${origin}] ${image.url}`;
+ });
+ const imageBlock = imageLines.length
+ ? `Reference images (served by PortOS at these paths — study them for palette, composition, texture, and lighting):\n${imageLines.join('\n')}`
+ : '';
+ if (!sections.length && !imageBlock) return '';
+ // The image list is short and bounded; the free text gives way first.
+ const textBudget = MAX_STYLE_SOURCE_LEN - STYLE_SOURCE_HEADER.length - 1 - (imageBlock ? imageBlock.length + 2 : 0);
+ const text = clamp(sections.join('\n\n'), Math.max(0, textBudget));
+ return `${STYLE_SOURCE_HEADER}\n${[text, imageBlock].filter(Boolean).join('\n\n')}`;
+}
+
+/**
+ * Resolve a commission's configured universe / mood board. Returns null when
+ * neither is configured (or both were deleted), else
+ * `{ universeId, universeName, moodBoardId, moodBoardName, text }`.
+ */
+export async function resolveCommissionStyleSource(commission) {
+ const constraints = commission?.brief?.constraints || {};
+ const universeId = isNonBlankStr(constraints.universeId) ? constraints.universeId : null;
+ const slots = COMMISSION_STYLE_REFERENCE_IMAGES_MAX;
+ const universe = universeId
+ ? await orSkipMissing(`universe ${universeId}`, resolveUniverseStyleSource(universeId, { imageSlots: slots }), null)
+ : null;
+ const boardChoice = constraints.moodBoardId;
+ const moodBoardId = boardChoice == null ? universe?.moodBoardId || null : (isNonBlankStr(boardChoice) ? boardChoice : null);
+ const universeImages = universe?.images || [];
+ const { board, images: boardImages } = moodBoardId
+ ? await orSkipMissing(
+ `mood board ${moodBoardId}`,
+ resolveMoodBoardStyleSource(moodBoardId, { imageSlots: Math.max(0, slots - universeImages.length) }),
+ { board: null, images: [] },
+ )
+ : { board: null, images: [] };
+ if (!universe && !board) return null;
+ const text = renderCommissionStyleSource({ universe, board, images: [...universeImages, ...boardImages] });
+ return {
+ universeId: universe ? universeId : null,
+ universeName: universe?.name || null,
+ moodBoardId: board ? moodBoardId : null,
+ moodBoardName: board?.name || null,
+ text,
+ };
+}
+
+/**
+ * The CD project's styleSpec: the style-source base, then the commission's own
+ * style notes as refinements on top. The user's words are never cut for the
+ * base — the base shrinks to fit the project's styleSpec cap instead.
+ */
+export function composeCommissionStyleSpec(userStyleSpec, styleSource) {
+ const own = typeof userStyleSpec === 'string' ? userStyleSpec.trim() : '';
+ const base = styleSource?.text || '';
+ if (!base) return clamp(own, COMMISSION_STYLE_SPEC_MAX);
+ if (!own) return clamp(base, COMMISSION_STYLE_SPEC_MAX);
+ const label = 'Refinements for this commission (apply on top of the base above):';
+ const room = COMMISSION_STYLE_SPEC_MAX - own.length - label.length - 3;
+ if (room <= 0) return clamp(own, COMMISSION_STYLE_SPEC_MAX);
+ return `${clamp(base, room)}\n\n${label}\n${own}`;
+}
diff --git a/server/services/creativeCommissions/styleSource.test.js b/server/services/creativeCommissions/styleSource.test.js
new file mode 100644
index 0000000000..f6dae02188
--- /dev/null
+++ b/server/services/creativeCommissions/styleSource.test.js
@@ -0,0 +1,101 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const resolveUniverseMock = vi.fn();
+const resolveBoardMock = vi.fn();
+vi.mock('../creativeStyleSources.js', () => ({
+ resolveUniverseStyleSource: (...a) => resolveUniverseMock(...a),
+ resolveMoodBoardStyleSource: (...a) => resolveBoardMock(...a),
+}));
+
+const { resolveCommissionStyleSource, composeCommissionStyleSpec, COMMISSION_STYLE_REFERENCE_IMAGES_MAX } = await import('./styleSource.js');
+const { MAX_STYLE_SOURCE_LEN } = await import('./directive.js');
+const { COMMISSION_STYLE_SPEC_MAX } = await import('../../lib/creativeBriefLimits.js');
+
+const notFound = () => Object.assign(new Error('missing'), { code: 'NOT_FOUND' });
+const universe = (over = {}) => ({
+ name: 'Example Universe',
+ embrace: ['ink wash', 'muted teal'],
+ avoid: ['neon'],
+ styleNotes: 'quiet, patient framing',
+ styleReferences: [],
+ moodBoardId: 'linked-board',
+ images: [{ label: 'Harbor study', origin: 'universe', path: '/abs/a.png', url: '/data/image-refs/a.png' }],
+ ...over,
+});
+const board = { board: { name: 'Example Board', items: [{ caption: 'fog over water' }] }, images: [{ label: 'Pin', origin: 'mood-board', path: '/abs/b.png', url: '/data/images/b.png' }] };
+const commission = (constraints) => ({ brief: { intent: 'x', constraints } });
+
+beforeEach(() => {
+ resolveUniverseMock.mockReset().mockResolvedValue(universe());
+ resolveBoardMock.mockReset().mockResolvedValue(board);
+});
+
+describe('resolveCommissionStyleSource', () => {
+ it('returns null when no style source is configured', async () => {
+ expect(await resolveCommissionStyleSource(commission({}))).toBeNull();
+ expect(resolveUniverseMock).not.toHaveBeenCalled();
+ });
+
+ it('follows the universe’s linked board and renders tags, notes, the board, and served image paths', async () => {
+ const source = await resolveCommissionStyleSource(commission({ universeId: 'u1' }));
+ expect(resolveBoardMock).toHaveBeenCalledWith('linked-board', { imageSlots: COMMISSION_STYLE_REFERENCE_IMAGES_MAX - 1 });
+ expect(source).toMatchObject({ universeId: 'u1', universeName: 'Example Universe', moodBoardId: 'linked-board', moodBoardName: 'Example Board' });
+ expect(source.text).toContain('Visual style to embrace: ink wash, muted teal');
+ expect(source.text).toContain('Visual style to avoid: neon');
+ expect(source.text).toContain('quiet, patient framing');
+ expect(source.text).toContain('fog over water');
+ expect(source.text).toContain('/data/image-refs/a.png');
+ expect(source.text).toContain('/data/images/b.png');
+ // Absolute machine paths never reach the prompt / synced project record.
+ expect(source.text).not.toContain('/abs/');
+ });
+
+ it("honors '' as no board and an explicit id over the universe's link", async () => {
+ const none = await resolveCommissionStyleSource(commission({ universeId: 'u1', moodBoardId: '' }));
+ expect(resolveBoardMock).not.toHaveBeenCalled();
+ expect(none.moodBoardId).toBeNull();
+
+ await resolveCommissionStyleSource(commission({ universeId: 'u1', moodBoardId: 'b2' }));
+ expect(resolveBoardMock).toHaveBeenCalledWith('b2', expect.any(Object));
+ });
+
+ it('works from a mood board alone', async () => {
+ const source = await resolveCommissionStyleSource(commission({ moodBoardId: 'b2' }));
+ expect(resolveUniverseMock).not.toHaveBeenCalled();
+ expect(source).toMatchObject({ universeId: null, moodBoardId: 'b2' });
+ expect(source.text).toContain('Example Board');
+ });
+
+ it('skips a deleted universe or board instead of failing the fire, but propagates outages', async () => {
+ resolveUniverseMock.mockRejectedValueOnce(notFound());
+ const source = await resolveCommissionStyleSource(commission({ universeId: 'gone', moodBoardId: 'b2' }));
+ expect(source).toMatchObject({ universeId: null, moodBoardId: 'b2' });
+
+ resolveUniverseMock.mockRejectedValueOnce(notFound());
+ resolveBoardMock.mockRejectedValueOnce(notFound());
+ expect(await resolveCommissionStyleSource(commission({ universeId: 'gone', moodBoardId: 'gone' }))).toBeNull();
+
+ resolveUniverseMock.mockRejectedValueOnce(new Error('connection refused'));
+ await expect(resolveCommissionStyleSource(commission({ universeId: 'u1' }))).rejects.toThrow('connection refused');
+ });
+
+ it('bounds the rendered base while keeping the image list', async () => {
+ resolveUniverseMock.mockResolvedValue(universe({ styleNotes: 'z'.repeat(10_000) }));
+ const source = await resolveCommissionStyleSource(commission({ universeId: 'u1' }));
+ expect(source.text.length).toBeLessThanOrEqual(MAX_STYLE_SOURCE_LEN);
+ expect(source.text).toContain('/data/images/b.png');
+ });
+});
+
+describe('composeCommissionStyleSpec', () => {
+ it('layers the commission’s own notes on top of the base and never cuts them for it', () => {
+ expect(composeCommissionStyleSpec('flat color', null)).toBe('flat color');
+ const spec = composeCommissionStyleSpec('flat color', { text: 'BASE' });
+ expect(spec.indexOf('BASE')).toBeLessThan(spec.indexOf('flat color'));
+
+ const own = 'y'.repeat(COMMISSION_STYLE_SPEC_MAX - 100);
+ const long = composeCommissionStyleSpec(own, { text: 'b'.repeat(MAX_STYLE_SOURCE_LEN) });
+ expect(long.length).toBeLessThanOrEqual(COMMISSION_STYLE_SPEC_MAX);
+ expect(long).toContain(own);
+ });
+});
diff --git a/server/services/creativeStyleSources.js b/server/services/creativeStyleSources.js
new file mode 100644
index 0000000000..85b692d3eb
--- /dev/null
+++ b/server/services/creativeStyleSources.js
@@ -0,0 +1,120 @@
+/**
+ * Style sources — resolve a universe's style guide and a mood board into
+ * prompt-ready art direction plus local reference images.
+ *
+ * Shared by every surface that lets the user pick "a universe or a mood board"
+ * as the look of a generation: Code Animation (prompt + brief writer) and
+ * Creative Commissions (the style base a scheduled fire hands the Creative
+ * Director). One resolver keeps the two from disagreeing about which tokens,
+ * notes, and images a universe or board contributes.
+ *
+ * The universe and mood-board stores are imported lazily so callers that only
+ * build prompts stay light in tests.
+ */
+
+import { ServerError } from '../lib/errorHandler.js';
+import { resolveGalleryImage, resolveImageRef } from '../lib/pathSafety.js';
+import { universeVisualStyleTokens } from '../lib/universeVisualStyle.js';
+import { isNonBlankStr, trimTo } from '../lib/textUtils.js';
+
+// The two served image dirs a reference can live in, by asset kind.
+const IMAGE_DIRS = {
+ 'image-ref': { resolve: resolveImageRef, urlPrefix: '/data/image-refs/' },
+ image: { resolve: resolveGalleryImage, urlPrefix: '/data/images/' },
+};
+
+// A local image as a prompt reference, or null when the file is missing.
+function localReference(kind, filename, label, origin) {
+ const dir = IMAGE_DIRS[kind];
+ const path = dir?.resolve(filename);
+ return path ? { label, origin, path, url: `${dir.urlPrefix}${encodeURIComponent(filename)}` } : null;
+}
+
+// Resolve reference candidates in order until `slots` are filled, so a
+// universe or board with many images costs only the stats it can use.
+function fillReferences(candidates, slots) {
+ const images = [];
+ for (const candidate of candidates) {
+ if (images.length >= slots) break;
+ const image = candidate();
+ if (image && !images.some((existing) => existing.path === image.path)) images.push(image);
+ }
+ return images;
+}
+
+// The narrative half of a universe — its bible text and canon arrays, passed
+// through for `renderCanonForPrompt` to project. Only a caller that writes
+// story (the Code Animation brief writer) asks for it: art-direction prompts
+// would just be crowded by a logline or a character's motivations.
+function universeNarrative(universe) {
+ const { characters, places, objects } = universe;
+ return {
+ logline: trimTo(universe.logline, 2_000),
+ premise: trimTo(universe.premise, 4_000),
+ characters,
+ places,
+ objects,
+ };
+}
+
+/**
+ * A universe's style guide: its embrace/avoid tokens, curated style references,
+ * style notes, linked mood board id, and up to `imageSlots` local style images.
+ * Throws a 404 `NOT_FOUND` ServerError when the universe does not exist.
+ */
+export async function resolveUniverseStyleSource(universeId, { imageSlots, narrative = false }) {
+ if (!universeId) return null;
+ const { getUniverse } = await import('./universeBuilder/crud.js');
+ const universe = await getUniverse(universeId).catch((error) => {
+ if (error?.code === 'NOT_FOUND') throw new ServerError('Universe not found', { status: 404, code: 'NOT_FOUND' });
+ throw error;
+ });
+ const { embrace, avoid } = universeVisualStyleTokens(universe);
+ const refs = Array.isArray(universe.styleReferences) ? universe.styleReferences : [];
+ const styleReferences = refs
+ .filter((ref) => isNonBlankStr(ref?.prompt))
+ .slice(0, 6)
+ .map((ref) => ({ title: trimTo(ref.title, 120), prompt: trimTo(ref.prompt, 600) }));
+ // A style image lives in either served dir depending on how it was made
+ // (style-reference upload vs gallery probe), so try refs first, then gallery.
+ const styleImage = (filename, label) => () => localReference('image-ref', filename, label, 'universe')
+ || localReference('image', filename, label, 'universe');
+ const candidates = [
+ ...refs.map((ref) => [ref?.imageRefs?.[0], trimTo(ref?.title, 120) || 'Universe style reference']),
+ ...(Array.isArray(universe.styleImageRefs) ? universe.styleImageRefs : []).map((filename) => [filename, 'Universe style probe']),
+ ].filter(([filename]) => isNonBlankStr(filename)).map(([filename, label]) => styleImage(filename, label));
+ const images = fillReferences(candidates, imageSlots);
+ return {
+ name: universe.name,
+ embrace,
+ avoid,
+ styleNotes: trimTo(universe.styleNotes, 2_000),
+ styleReferences,
+ moodBoardId: isNonBlankStr(universe.moodBoardId) ? universe.moodBoardId : null,
+ images,
+ ...(narrative ? universeNarrative(universe) : {}),
+ };
+}
+
+/**
+ * A mood board's style context (`collectBoardStyleContext`) plus up to
+ * `imageSlots` of its local pinned images. Throws a 404 `NOT_FOUND`
+ * ServerError when the board does not exist.
+ */
+export async function resolveMoodBoardStyleSource(moodBoardId, { imageSlots }) {
+ if (!moodBoardId) return { board: null, images: [] };
+ const [{ getBoard }, { collectBoardStyleContext }, { boardItemLocalImage }] = await Promise.all([
+ import('./moodBoard/db.js'),
+ import('./moodBoard/styleContext.js'),
+ import('./moodBoard/logic.js'),
+ ]);
+ const board = await getBoard(moodBoardId);
+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
+ // Text items, videos, and external pins attach nothing — they still
+ // contribute their caption/analysis text through the board context.
+ const candidates = (board.items || []).map((item) => () => {
+ const asset = boardItemLocalImage(item);
+ return asset ? localReference(asset.kind, asset.filename, trimTo(item.caption, 120) || asset.filename, 'mood-board') : null;
+ });
+ return { board: collectBoardStyleContext(board), images: fillReferences(candidates, imageSlots) };
+}