Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1808]): seed Creative Director projects from catalog ingredients
Adam Eivy8da370b1907b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d9fc106a61..7668db9dd8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,10 @@- **[issue-1762] Catalog gains universe/series/tag filters, real pagination, and an Albums grouped view.** The Catalog page had outgrown a flat, hard-capped list of 200 ingredients with only type chips + search. It now exposes the universe, series, and tag facets the server already understood as filter dropdowns (series scoped to the chosen universe), all reflected in the URL (`?type=&universe=&series=&tag=&q=&view=`) so a filtered catalog is shareable and back-button-safe. The flat Grid view paginates past the old cap with a "Load more" button (60/page) and an honest "showing X of N" line. A new **Albums** view groups ingredients by universe with a pinned **"Unsorted / Raw"** album (ingredients linked to nothing yet) and an **"Orphaned"** album (refs whose universe/series was deleted) — each lazy-loading its cards on first expand. The multi-select action bar can now **place a selection into a universe/series** directly, closing the raw → placed loop. Server-side: `listIngredients` gained `refKind`/`refId`/`unlinked`/`orphaned` filters, a new `GET /api/catalog/facets` aggregates type/universe/series/tag facets plus unlinked/orphaned bucket counts in one round-trip, and the shared `<CatalogCard>` is extracted so the grid and albums render identical cards. (`server/services/catalogDB.js`, `server/routes/catalog.js`, `server/lib/catalogValidation.js`, `client/src/pages/Catalog.jsx`, `client/src/components/catalog/`, `client/src/services/apiCatalog.js`)+## Creative Director++- **[issue-1808] Remix catalog ingredients straight into a Creative Director project.** The Catalog's "Remix into…" menu (multi-select ingredients) now offers **Creative Director** alongside Story Builder. Hand a set of characters, places, objects, or scenes to the Creative Director and they arrive as the project's **cast**: the create form shows them as chips, and the autonomous director uses them when it writes the treatment — grounding the story in your canon and **casting specific members into individual scenes** so renders stay on-model. The seeded ingredients are also linked back to the project in the catalog, so each one's "Appears in" list now shows the Creative Director projects it features in. (Closes #1808)+## Music Video production mode- **[issue-1760] Groundwork: offline beat/tempo/section analysis of an audio track (Phase 0 spike).** The first slice of the planned Music Video production mode proves the riskiest unknown — that a music track's BPM, beat grid, 4/4 downbeats, and a coarse section map can be extracted **fully offline with no new dependency**, using only ffmpeg (already required) plus a pure-JS DSP core (onset-strength envelope → tempo-weighted autocorrelation → beat-phase fit → energy-novelty sections). No Python, no ML model download, no network — so it runs the same in CI and on every install. There's no user-facing surface yet; this is the analyzer the upcoming director scene board and beat-snapped render build on. (`server/services/musicVideo/audioAnalysis.js`)diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsxindex 4b05f9c672..2e24e2f73d 100644--- a/client/src/pages/Catalog.jsx+++ b/client/src/pages/Catalog.jsx@@ -51,6 +51,7 @@ const PAGE_SIZE = 60;// reads the same key. Each target's `to` is the route to navigate to.const REMIX_TARGETS = [{ id: 'story-builder', label: 'Story Builder', to: '/story-builder' },+ { id: 'creative-director', label: 'Creative Director', to: '/media/creative-director' },];export default function Catalog() {diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsxindex d04ad2d262..54d526d42b 100644--- a/client/src/pages/CreativeDirector.jsx+++ b/client/src/pages/CreativeDirector.jsx@@ -1,6 +1,6 @@import { useEffect, useState, useCallback } from 'react';-import { Link } from 'react-router-dom';-import { Plus, Film, Trash2, Play, Pause, FlaskConical } from 'lucide-react';+import { Link, useLocation, useNavigate } from 'react-router-dom';+import { Plus, Film, Trash2, Play, Pause, FlaskConical, Sparkles } from 'lucide-react';import toast from '../components/ui/Toast';import {listCreativeDirectorProjects,@@ -10,6 +10,7 @@ import {startCreativeDirectorProject,pauseCreativeDirectorProject,} from '../services/apiCreativeDirector.js';+import { listCatalogIngredientsByIds } from '../services/apiCatalog.js';import { listVideoModels } from '../services/apiImageVideo.js';import ModelSelect from '../components/ModelSelect';import PageHeader from '../components/PageHeader';@@ -28,10 +29,18 @@ const STATUS_COLORS = {};export default function CreativeDirector() {+ const location = useLocation();+ const navigate = useNavigate();const [projects, setProjects] = useState([]);const [loading, setLoading] = useState(true);const [showForm, setShowForm] = useState(false);const [models, setModels] = useState([]);+ // Catalog "Remix into… → Creative Director" handoff (#1808). The ingredient+ // ids arrive in the generic `location.state.remix.ingredientIds`; we hydrate+ // them for the chip list and forward the ids on create so the server folds+ // them into the project cast + links catalog_ingredient_refs.+ const [remixIds, setRemixIds] = useState([]);+ const [remixIngredients, setRemixIngredients] = useState([]);const [form, setForm] = useState({name: '',aspectRatio: '16:9',@@ -64,6 +73,23 @@ export default function CreativeDirector() {}).catch(() => {});}, [fetchProjects]);+ // Consume the remix handoff once at mount, then clear the history state so a+ // refresh doesn't re-seed (mirrors Story Builder's prefill-consume pattern).+ // Auto-open the create form so the seeded ingredient chips are visible.+ useEffect(() => {+ const ids = location.state?.remix?.ingredientIds;+ if (!Array.isArray(ids) || ids.length === 0) return;+ const cleanIds = ids.filter(Boolean).slice(0, 50);+ if (cleanIds.length === 0) return;+ setRemixIds(cleanIds);+ setShowForm(true);+ listCatalogIngredientsByIds(cleanIds, { silent: true })+ .then((res) => setRemixIngredients(Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : [])))+ .catch(() => {});+ // Clear the handoff state so a refresh doesn't re-seed (ids already captured).+ navigate('.', { replace: true, state: {} });+ }, []);+const handleCreate = async (e) => {e.preventDefault();if (!form.name.trim() || !form.modelId) {@@ -80,6 +106,9 @@ export default function CreativeDirector() {userStory: form.userStory || null,startingImageFile: form.startingImageFile || null,disableAudio: form.disableAudio,+ // Catalog remix handoff (#1808): the server resolves these into the+ // project cast + catalog_ingredient_refs.+ ...(remixIds.length ? { catalogIngredientIds: remixIds } : {}),};try {const created = await createCreativeDirectorProject(payload);@@ -87,6 +116,13 @@ export default function CreativeDirector() {setShowForm(false);setForm((f) => ({ ...f, name: '', styleSpec: '', userStory: '', startingImageFile: '' }));toast.success(`Created "${created.name}"`);+ // Land on the seeded project's overview when ingredients were remixed in+ // so the user sees the cast immediately; otherwise stay on the list.+ if (remixIds.length) {+ setRemixIds([]);+ setRemixIngredients([]);+ navigate(`/media/creative-director/${created.id}/overview`);+ }} catch (err) {toast.error(err.message || 'Failed to create project');}@@ -168,6 +204,27 @@ export default function CreativeDirector() {{showForm && (<form onSubmit={handleCreate} className="shrink-0 p-6 border-b border-port-border bg-port-card/40 space-y-3">+ {remixIngredients.length > 0 && (+ <div className="rounded border border-port-accent/40 bg-port-accent/10 px-3 py-2">+ <div className="text-xs uppercase tracking-wide text-port-accent mb-1.5">+ Casting from {remixIngredients.length} catalog ingredient{remixIngredients.length === 1 ? '' : 's'}+ </div>+ <div className="flex flex-wrap gap-1.5">+ {remixIngredients.map((ing) => (+ <span+ key={ing.id}+ className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-gray-200"+ >+ <Sparkles className="w-3 h-3 text-port-accent" aria-hidden="true" />+ {ing.name || '(untitled)'}+ </span>+ ))}+ </div>+ <p className="text-xs text-port-text-muted mt-1.5">+ These become the project cast — the Creative Director grounds the treatment and per-scene casting on them.+ </p>+ </div>+ )}<div className="grid grid-cols-1 md:grid-cols-2 gap-3"><label className="block text-sm"><span className="text-port-text-muted">Name</span>diff --git a/data.reference/prompts/stages/cd-treatment.md b/data.reference/prompts/stages/cd-treatment.mdindex 9455ef3778..0d60c0f84e 100644--- a/data.reference/prompts/stages/cd-treatment.md+++ b/data.reference/prompts/stages/cd-treatment.md@@ -16,6 +16,16 @@ You are the Creative Director for a long-form generated-video project. Your job{{#project.styleSpec}}{{project.styleSpec}}{{/project.styleSpec}}{{^project.styleSpec}}(none — derive a coherent visual language from the project name + first scene intent){{/project.styleSpec}}+{{#hasCast}}+## Cast & ingredients++The user seeded this project with the following catalog ingredients (characters, places, objects, scenes). Treat them as canon — feature them, keep them visually consistent across scenes, and don't contradict their descriptions. For any scene that features specific members, list them in that scene's optional `cast` array (by `ingredientId` + `name` + `role`) so the render stays on-model.++{{#project.cast}}+- **{{name}}** ({{type}} · {{role}}, id `{{ingredientId}}`){{#summary}}: {{summary}}{{/summary}}+{{/project.cast}}+{{/hasCast}}+{{#project.userStory}}## User-supplied story@@ -58,7 +68,8 @@ Content-Type: application/json"durationSeconds": 5,"useContinuationFromPrior": false,"sourceImageFile": {{startingImageFileLiteral}},- "imageStrength": null+ "imageStrength": null{{#hasCast}},+ "cast": [{ "ingredientId": "<id from the Cast list above>", "name": "<member name>", "role": "<cast|location|prop>" }]{{/hasCast}}},{ "sceneId": "scene-2", "order": 1, ..., "useContinuationFromPrior": true, "imageStrength": 0.85 }]diff --git a/scripts/migrations/148-cd-treatment-catalog-cast.js b/scripts/migrations/148-cd-treatment-catalog-cast.jsnew file mode 100644index 0000000000..21a9aa3452--- /dev/null+++ b/scripts/migrations/148-cd-treatment-catalog-cast.js@@ -0,0 +1,97 @@+/**+ * Backfill the catalog-cast surfacing in cd-treatment.md for pre-existing+ * installs (#1808).+ *+ * The Creative Director treatment template gained a `## Cast & ingredients`+ * block (rendered from the project's `cast` array, seeded via the Catalog+ * "Remix into → Creative Director" handoff) plus an optional per-scene `cast`+ * field in the JSON output contract. `setup-data.js` only copies prompt files+ * that don't yet exist in `data/`, so installs created before this change never+ * received the new blocks — the cast-threading regression tests in+ * `creativeDirectorPrompts.test.js` fail until the local copy catches up.+ *+ * This migration surgically inserts the two missing pieces ONLY when the+ * surrounding anchor text matches the pre-update content exactly — so a user+ * who has hand-edited the template won't have their work clobbered. If anchors+ * don't match, it logs a notice and exits cleanly; the user can hand-merge from+ * data.reference/ or accept the cast tests staying red on their machine.+ *+ * Idempotent — re-runs are a no-op once `{{#hasCast}}` is present.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const TEMPLATE_REL_PATH = 'data/prompts/stages/cd-treatment.md';++// Insertion 1: the `## Cast & ingredients` section, dropped between the style+// spec block and the user-story branch. The anchor pair brackets the insertion+// point; the last `{{/project.styleSpec}}` (the one followed by a blank line ++// the user-story section) is what makes the pair unique on that line.+const ANCHOR_STYLE_END = '{{/project.styleSpec}}\n\n';+const ANCHOR_USER_STORY = '{{#project.userStory}}';+const CAST_SECTION =+ '{{#hasCast}}\n' ++ '## Cast & ingredients\n' ++ '\n' ++ 'The user seeded this project with the following catalog ingredients (characters, places, objects, scenes). Treat them as canon — feature them, keep them visually consistent across scenes, and don\'t contradict their descriptions. For any scene that features specific members, list them in that scene\'s optional `cast` array (by `ingredientId` + `name` + `role`) so the render stays on-model.\n' ++ '\n' ++ '{{#project.cast}}\n' ++ '- **{{name}}** ({{type}} · {{role}}, id `{{ingredientId}}`){{#summary}}: {{summary}}{{/summary}}\n' ++ '{{/project.cast}}\n' ++ '{{/hasCast}}\n' ++ '\n';++// Insertion 2: the optional per-scene `cast` field in the JSON output contract.+// Anchor the scene-1 example's imageStrength line + the object close; append a+// gated `cast` array after `imageStrength`.+const SCENE_OLD = ' "imageStrength": null\n },';+const SCENE_NEW =+ ' "imageStrength": null{{#hasCast}},\n' ++ ' "cast": [{ "ingredientId": "<id from the Cast list above>", "name": "<member name>", "role": "<cast|location|prop>" }]{{/hasCast}}\n' ++ ' },';++export default {+ async up({ rootDir }) {+ const templatePath = join(rootDir, TEMPLATE_REL_PATH);+ const original = await readFile(templatePath, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (original == null) {+ console.log(`📄 ${TEMPLATE_REL_PATH} not present — skipping (fresh install will copy from data.reference)`);+ return;+ }++ let next = original;+ let changed = false;++ // Insertion 1: the Cast section.+ if (!next.includes('{{#hasCast}}')) {+ const anchorPair = ANCHOR_STYLE_END + ANCHOR_USER_STORY;+ if (next.includes(anchorPair)) {+ next = next.replace(anchorPair, ANCHOR_STYLE_END + CAST_SECTION + ANCHOR_USER_STORY);+ changed = true;+ } else {+ console.log(`⚠️ ${TEMPLATE_REL_PATH}: style-spec/user-story anchors don't match the pre-update template — skipping the Cast block insertion. Hand-merge from data.reference/ if needed.`);+ }+ }++ // Insertion 2: the per-scene cast JSON field.+ if (!next.includes('"cast": [{ "ingredientId"')) {+ if (next.includes(SCENE_OLD)) {+ next = next.replace(SCENE_OLD, SCENE_NEW);+ changed = true;+ } else {+ console.log(`⚠️ ${TEMPLATE_REL_PATH}: scene JSON example anchor doesn't match the pre-update template — skipping the per-scene cast insertion. Hand-merge from data.reference/ if needed.`);+ }+ }++ if (changed) {+ await writeFile(templatePath, next);+ console.log(`📝 ${TEMPLATE_REL_PATH}: backfilled catalog-cast surfacing (#1808)`);+ } else {+ console.log(`✅ ${TEMPLATE_REL_PATH}: already up-to-date, no changes needed`);+ }+ },+};diff --git a/scripts/migrations/148-cd-treatment-catalog-cast.test.js b/scripts/migrations/148-cd-treatment-catalog-cast.test.jsnew file mode 100644index 0000000000..ac2b27cc0f--- /dev/null+++ b/scripts/migrations/148-cd-treatment-catalog-cast.test.js@@ -0,0 +1,90 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './148-cd-treatment-catalog-cast.js';++const REL = 'data/prompts/stages/cd-treatment.md';++// Minimal pre-change template carrying both migration anchors verbatim: the+// style-spec → user-story bracket (Insertion 1) and the scene JSON example's+// imageStrength line (Insertion 2).+const PRE_TEMPLATE = [+ '## Style spec (apply to every prompt)',+ '',+ '{{#project.styleSpec}}{{project.styleSpec}}{{/project.styleSpec}}{{^project.styleSpec}}(none){{/project.styleSpec}}',+ '',+ '{{#project.userStory}}',+ '## User-supplied story',+ '',+ '{{project.userStory}}',+ '{{/project.userStory}}',+ '',+ '```',+ '{',+ ' "scenes": [',+ ' {',+ ' "sourceImageFile": {{startingImageFileLiteral}},',+ ' "imageStrength": null',+ ' },',+ ' { "sceneId": "scene-2" }',+ ' ]',+ '}',+ '```',+ '',+].join('\n');++describe('migration 148 — backfill cd-treatment catalog cast', () => {+ let rootDir;+ let templatePath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-148-'));+ templatePath = join(rootDir, REL);+ mkdirSync(join(rootDir, 'data', 'prompts', 'stages'), { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('inserts the Cast section and per-scene cast field into a pristine template', async () => {+ writeFileSync(templatePath, PRE_TEMPLATE);+ await migration.up({ rootDir });+ const out = readFileSync(templatePath, 'utf-8');++ // Insertion 1: the header-once flag + section + member iteration land+ // between the style spec and the user-story branch.+ expect(out).toContain('{{#hasCast}}');+ expect(out).toContain('## Cast & ingredients');+ expect(out).toContain('{{#project.cast}}');+ expect(out.indexOf('{{#hasCast}}')).toBeLessThan(out.indexOf('{{#project.userStory}}'));+ expect(out.indexOf('{{/project.styleSpec}}')).toBeLessThan(out.indexOf('{{#hasCast}}'));++ // Insertion 2: the gated per-scene cast field follows imageStrength.+ expect(out).toContain('"cast": [{ "ingredientId":');+ expect(out).toContain('"imageStrength": null{{#hasCast}},');+ });++ it('is idempotent — a second run makes no further changes', async () => {+ writeFileSync(templatePath, PRE_TEMPLATE);+ await migration.up({ rootDir });+ const afterFirst = readFileSync(templatePath, 'utf-8');+ await migration.up({ rootDir });+ const afterSecond = readFileSync(templatePath, 'utf-8');+ expect(afterSecond).toBe(afterFirst);+ });++ it('leaves a hand-edited template (anchors absent) untouched without throwing', async () => {+ const edited = '# Totally different template\n\nNo anchors here.\n';+ writeFileSync(templatePath, edited);+ await migration.up({ rootDir });+ expect(readFileSync(templatePath, 'utf-8')).toBe(edited);+ });++ it('skips cleanly when the template file is absent (fresh install)', async () => {+ // No file written — must not throw.+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ });+});diff --git a/server/lib/creativeDirectorPrompts.js b/server/lib/creativeDirectorPrompts.jsindex 4628d70292..1931f2dcbe 100644--- a/server/lib/creativeDirectorPrompts.js+++ b/server/lib/creativeDirectorPrompts.js@@ -44,6 +44,10 @@ function buildProjectView(project) {startingImageFile: project.startingImageFile || '',styleSpec: project.styleSpec || '',userStory: project.userStory || '',+ // Catalog cast seeded via "Remix into → Creative Director" (#1808). Each+ // member: { ingredientId, name, type, role, summary? }. Empty array for a+ // bare project so the template's `{{#project.cast}}` section stays hidden.+ cast: Array.isArray(project.cast) ? project.cast : [],};}@@ -56,12 +60,17 @@ function buildTreatmentView(project) {const startingImageFileLiteral = project.startingImageFile? `"${project.startingImageFile}"`: 'null';+ // Header-once flag for the template's `## Cast` block — the `{{#project.cast}}`+ // section iterates the members, so a separate boolean renders the heading ++ // intro exactly once (and hides them entirely for a bare project).+ const hasCast = Array.isArray(project.cast) && project.cast.length > 0;return {project: buildProjectView(project),aspect,quality,apiUrl: PORTOS_API_URL,startingImageFileLiteral,+ hasCast,};}diff --git a/server/lib/creativeDirectorPrompts.test.js b/server/lib/creativeDirectorPrompts.test.jsindex 59e94dcdf3..8d14b15fe4 100644--- a/server/lib/creativeDirectorPrompts.test.js+++ b/server/lib/creativeDirectorPrompts.test.js@@ -99,6 +99,32 @@ describe('buildTreatmentPrompt — template-rendered output', () => {expect(out).toContain('"sourceImageFile": "hero.png"');expect(out).toContain('Starting image: /data/images/hero.png');});++ it('hides the Cast section + per-scene cast field when no cast is seeded (#1808)', async () => {+ const out = await buildTreatmentPrompt(baseProject);+ expect(out).not.toContain('## Cast & ingredients');+ expect(out).not.toContain('"cast"');+ });++ it('renders the Cast section + per-scene cast field when ingredients are seeded (#1808)', async () => {+ const out = await buildTreatmentPrompt({+ ...baseProject,+ cast: [+ { ingredientId: 'cat-c', name: 'Mara', type: 'character', role: 'cast', summary: 'A tall figure in a grey coat.' },+ { ingredientId: 'cat-p', name: 'The Spire', type: 'place', role: 'location' },+ ],+ });+ expect(out).toContain('## Cast & ingredients');+ // Member lines render name, type · role, id, and the optional summary.+ expect(out).toContain('**Mara** (character · cast, id `cat-c`): A tall figure in a grey coat.');+ // No summary → the `{{#summary}}` block stays empty (no trailing colon).+ expect(out).toContain('**The Spire** (place · location, id `cat-p`)');+ expect(out).not.toContain('**The Spire** (place · location, id `cat-p`):');+ // The header + intro render exactly once, not per member.+ expect(out.match(/## Cast & ingredients/g)).toHaveLength(1);+ // The per-scene cast field appears in the JSON output contract.+ expect(out).toContain('"cast": [{ "ingredientId":');+ });});describe('buildEvaluatePrompt — multi-frame sampling', () => {diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex f80487e8eb..5951f20618 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -36,6 +36,20 @@ const safeBasename = z.string().refine((v) => v !== '.' && v !== '..','must not be `.` or `..`');+// One cast member — a catalog ingredient seeded into the project (#1808). Stored+// on the project record and surfaced to the treatment agent for grounding ++// per-scene casting. `ingredientId` is the stable catalog id so the agent (and a+// future casting UI) can reference a specific member. The server derives this+// array from `catalogIngredientIds`; it's accepted on the wire too so a direct+// API caller (or a sync round-trip) can supply it explicitly.+export const creativeDirectorCastMemberSchema = z.object({+ ingredientId: z.string().min(1).max(64),+ name: z.string().min(1).max(200),+ type: z.string().max(64).optional(),+ role: z.string().max(64).optional(),+ summary: z.string().max(500).optional(),+});+export const creativeDirectorProjectCreateSchema = z.object({name: z.string().min(1).max(200),aspectRatio: creativeDirectorAspectRatioSchema,@@ -45,6 +59,14 @@ export const creativeDirectorProjectCreateSchema = z.object({styleSpec: z.string().max(5000).default(''),startingImageFile: safeBasename.nullable().optional(),userStory: z.string().max(10000).nullable().optional(),+ // Catalog "Remix into → Creative Director" handoff (#1761/#1808): the selected+ // ingredient ids. The service resolves them to live records, folds them into+ // the project `cast`, and links them via catalog_ingredient_refs. Bounded to+ // 50 to match the remix multi-select cap.+ catalogIngredientIds: z.array(z.string().trim().max(64)).max(50).optional(),+ // Server-derived from catalogIngredientIds; also accepted directly for off-UI+ // callers and sync. Schema-parity with buildProjectRecord's `cast` field.+ cast: z.array(creativeDirectorCastMemberSchema).max(50).optional(),// Audio defaults OFF for CD projects — current model audio output is// inconsistent across renders and the user can re-enable per-project.// (videoGen one-offs still default to enabled.)@@ -96,6 +118,11 @@ export const creativeDirectorSceneSchema = z.object({status: z.enum(SCENE_STATUSES).default('pending'),retryCount: z.number().int().min(0).max(10).default(0),renderedJobId: z.string().max(64).nullable().optional(),+ // Per-scene casting (#1808) — the catalog cast members the agent bound to this+ // scene, referencing the project `cast` by ingredientId. Optional: the agent+ // only sets it when a scene features specific characters/places, and bare+ // (non-remix) projects never carry it.+ cast: z.array(creativeDirectorCastMemberSchema).max(20).optional(),evaluation: z.object({score: z.number().min(0).max(1).optional(),notes: z.string().max(2000).optional(),diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex 6cf027946d..4b85de97d2 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -977,6 +977,33 @@ export async function linkIngredientsToSeries(seriesId, ingredients = []) {return list;}+// Catalog ingredient `type` → Creative Director ref role (#1808). CD projects+// reuse the same convergence data model (catalog_ingredient_refs) as series; the+// role vocabulary is CD-flavored (location/prop) so the Catalog "Appears in"+// panel and any future casting UI can label a CD link meaningfully. Anything+// outside this map (idea/concept/user-defined types) links as a generic+// 'reference'. Lives next to seriesRefRoleForType so every remix target shares+// one role-vocabulary home.+const CD_REF_ROLE_BY_TYPE = Object.freeze({+ character: 'cast',+ place: 'location',+ object: 'prop',+ scene: 'scene',+});+export const cdRefRoleForType = (type) => CD_REF_ROLE_BY_TYPE[type] || 'reference';++// Link a batch of already-resolved catalog ingredients to a Creative Director+// project via catalog_ingredient_refs with ref_kind='creative-director' (#1808)+// — the reserved-but-previously-unwritten ref kind. Mirrors+// linkIngredientsToSeries; the inserts are independent so they fan out. Returns+// the ingredients actually linked (those with an id).+export async function linkIngredientsToCreativeDirector(projectId, ingredients = []) {+ const list = Array.isArray(ingredients) ? ingredients.filter((ing) => ing && ing.id) : [];+ if (list.length === 0) return [];+ await Promise.all(list.map((ing) => linkIngredientToRef(ing.id, 'creative-director', projectId, cdRefRoleForType(ing.type))));+ return list;+}+export async function unlinkIngredientFromRef(ingredientId, refKind, refId, role) {// Soft-delete via UPDATE so the row stays around as a tombstone and the// trg_catalog_ref_sync_seq trigger bumps sync_sequence — peers pick the@@ -1014,6 +1041,22 @@ export async function listIngredientsForRef(refKind, refId) {return result.rows.map((row) => ({ ingredient: rowToIngredient(row), role: row.role }));}+// Resolve a list of ingredient ids to live ingredient records in a single batch+// query (listIngredients already excludes soft-deleted rows), de-duped and+// re-ordered to the caller's pick order so a composed seed/cast reads in the+// order the user selected. Missing/deleted ids are simply absent and skipped.+// Shared by every remix target (#1761 Story Builder seed, #1808 Creative+// Director cast) so the resolve logic lives in one place next to the data layer.+export async function resolveIngredientsByIds(ids) {+ const list = [...new Set((Array.isArray(ids) ? ids : [])+ .filter((id) => typeof id === 'string' && id.trim())+ .map((id) => id.trim()))];+ if (list.length === 0) return [];+ const { items } = await listIngredients({ ids: list, limit: list.length });+ const byId = new Map(items.map((ing) => [ing.id, ing]));+ return list.map((id) => byId.get(id)).filter(Boolean);+}+// --- Ingredient↔ingredient relations -----------------------------------// Directed edges (from_id → to_id, kind). Soft-deleted on unlink so peersdiff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.jsindex 2920492f8f..a119b4cd94 100644--- a/server/services/catalogDB.test.js+++ b/server/services/catalogDB.test.js@@ -76,6 +76,21 @@ describe('seriesRefRoleForType', () => {});});+// Pure helper — the type→Creative-Director-role vocabulary (#1808). No DB, so it+// runs in the normal suite and stays the single source of truth for the roles a+// CD remix uses when attaching ingredients to a project.+describe('cdRefRoleForType', () => {+ it('maps known types to CD roles and everything else to reference', () => {+ expect(catalogDB.cdRefRoleForType('character')).toBe('cast');+ expect(catalogDB.cdRefRoleForType('place')).toBe('location');+ expect(catalogDB.cdRefRoleForType('object')).toBe('prop');+ expect(catalogDB.cdRefRoleForType('scene')).toBe('scene');+ expect(catalogDB.cdRefRoleForType('idea')).toBe('reference');+ expect(catalogDB.cdRefRoleForType('faction')).toBe('reference'); // user-defined+ expect(catalogDB.cdRefRoleForType(undefined)).toBe('reference');+ });+});+describe.skipIf(!dbReady)('catalogDB (Postgres CRUD round-trip)', () => {it('creates and reads back an ingredient with payload + tags', async () => {if (!requireDb('create/get ingredient')) return;@@ -270,6 +285,45 @@ describe.skipIf(!dbReady)('catalogDB (Postgres CRUD round-trip)', () => {expect(await catalogDB.linkIngredientsToSeries(seriesId, [])).toEqual([]);});+ it('linkIngredientsToCreativeDirector batch-links with creative-director ref_kind + CD roles (#1808)', async () => {+ if (!requireDb('batch link to CD project')) return;+ const chr = await catalogDB.createIngredient({ type: 'character', name: 'CD Mira' });+ const plc = await catalogDB.createIngredient({ type: 'place', name: 'CD Foundry' });+ const obj = await catalogDB.createIngredient({ type: 'object', name: 'CD Relic' });+ [chr, plc, obj].forEach((i) => createdIngredientIds.add(i.id));+ const projectId = `cd-batch-${chr.id}`;++ const linked = await catalogDB.linkIngredientsToCreativeDirector(projectId, [chr, plc, obj]);+ expect(linked).toHaveLength(3);++ const forRef = await catalogDB.listIngredientsForRef('creative-director', projectId);+ const roleById = Object.fromEntries(forRef.map((r) => [r.ingredient.id, r.role]));+ expect(roleById[chr.id]).toBe('cast');+ expect(roleById[plc.id]).toBe('location');+ expect(roleById[obj.id]).toBe('prop');++ // The ref is visible from the ingredient side too, under the reserved kind.+ const refs = await catalogDB.listRefsForIngredient(chr.id);+ expect(refs.some((r) => r.refKind === 'creative-director' && r.refId === projectId)).toBe(true);++ // Empty / id-less input is a no-op.+ expect(await catalogDB.linkIngredientsToCreativeDirector(projectId, [])).toEqual([]);+ });++ it('resolveIngredientsByIds dedupes, preserves pick order, and skips missing ids (#1808)', async () => {+ if (!requireDb('resolve ingredients by ids')) return;+ const a = await catalogDB.createIngredient({ type: 'character', name: 'Resolve A' });+ const b = await catalogDB.createIngredient({ type: 'place', name: 'Resolve B' });+ [a, b].forEach((i) => createdIngredientIds.add(i.id));++ // Pick order is b, a (reversed), with a duplicate and a nonexistent id mixed in.+ const resolved = await catalogDB.resolveIngredientsByIds([b.id, a.id, b.id, 'cat-does-not-exist']);+ expect(resolved.map((i) => i.id)).toEqual([b.id, a.id]);++ expect(await catalogDB.resolveIngredientsByIds([])).toEqual([]);+ expect(await catalogDB.resolveIngredientsByIds(null)).toEqual([]);+ });+it('creates a scrap, links it as an ingredient source, and hydrates it back', async () => {if (!requireDb('scrap source link')) return;const scrap = await catalogDB.createScrap({diff --git a/server/services/creativeDirector/catalogSeed.js b/server/services/creativeDirector/catalogSeed.jsnew file mode 100644index 0000000000..8af7f65bba--- /dev/null+++ b/server/services/creativeDirector/catalogSeed.js@@ -0,0 +1,44 @@+/**+ * Creative Director — catalog ingredient seeding (#1808).+ *+ * Turns a list of resolved catalog ingredient records (characters / places /+ * objects / scenes / ideas) into the structured `cast` array stored on a CD+ * project and surfaced to the treatment agent. The agent uses the cast to ground+ * the treatment prompt and bind specific members to individual scenes (per-scene+ * casting). The same ingredients are linked to the project via+ * catalog_ingredient_refs (ref_kind='creative-director') — see+ * linkIngredientsToCreativeDirector in catalogDB.js — so the Catalog "Appears+ * in" panel and the convergence contract stay on one data model.+ *+ * Pure transform (no I/O), so it's unit-tested without a DB.+ */++import { cdRefRoleForType } from '../catalogDB.js';+import { getActiveCatalogType, payloadSnippet } from '../../lib/catalogTypes.js';++const CAST_SUMMARY_CHARS = 200;+// Mirrors the catalogIngredientIds cap on the create schema — a CD treatment+// with more than ~50 cast members is past the point the agent can reason about+// them per scene, and bounds the JSONB the project row carries.+const MAX_CAST = 50;++/**+ * Build the project `cast` array from resolved ingredient records. Each member+ * carries the stable ingredientId (so the agent can reference it in per-scene+ * casting), a display name, the source type, the CD ref role, and a short+ * payload summary (omitted when empty). Skips records without an id.+ */+export function buildCastFromIngredients(ingredients = []) {+ const list = Array.isArray(ingredients) ? ingredients.filter((ing) => ing && ing.id) : [];+ return list.slice(0, MAX_CAST).map((ing) => {+ const summary = payloadSnippet(ing.payload, ing.type, CAST_SUMMARY_CHARS, getActiveCatalogType);+ const name = (typeof ing.name === 'string' && ing.name.trim()) ? ing.name.trim() : '(untitled)';+ return {+ ingredientId: ing.id,+ name,+ type: ing.type || 'other',+ role: cdRefRoleForType(ing.type),+ ...(summary ? { summary } : {}),+ };+ });+}diff --git a/server/services/creativeDirector/catalogSeed.test.js b/server/services/creativeDirector/catalogSeed.test.jsnew file mode 100644index 0000000000..d06bde4cb7--- /dev/null+++ b/server/services/creativeDirector/catalogSeed.test.js@@ -0,0 +1,57 @@+import { describe, it, expect } from 'vitest';+import { buildCastFromIngredients } from './catalogSeed.js';++describe('buildCastFromIngredients (#1808)', () => {+ it('maps catalog types to CD ref roles', () => {+ const cast = buildCastFromIngredients([+ { id: 'c1', name: 'Mara', type: 'character', payload: {} },+ { id: 'p1', name: 'The Spire', type: 'place', payload: {} },+ { id: 'o1', name: 'Brass Key', type: 'object', payload: {} },+ { id: 's1', name: 'The Reveal', type: 'scene', payload: {} },+ { id: 'i1', name: 'Loose idea', type: 'idea', payload: {} },+ ]);+ expect(cast.map((m) => [m.type, m.role])).toEqual([+ ['character', 'cast'],+ ['place', 'location'],+ ['object', 'prop'],+ ['scene', 'scene'],+ ['idea', 'reference'], // unmapped → generic reference+ ]);+ });++ it('carries the stable ingredientId and a display name', () => {+ const [member] = buildCastFromIngredients([{ id: 'c1', name: ' Mara ', type: 'character', payload: {} }]);+ expect(member.ingredientId).toBe('c1');+ expect(member.name).toBe('Mara'); // trimmed+ });++ it('falls back to (untitled) for a blank name', () => {+ const [member] = buildCastFromIngredients([{ id: 'c1', name: ' ', type: 'character', payload: {} }]);+ expect(member.name).toBe('(untitled)');+ });++ it('omits summary when the payload yields nothing', () => {+ const [member] = buildCastFromIngredients([{ id: 'c1', name: 'Mara', type: 'character', payload: {} }]);+ expect(member).not.toHaveProperty('summary');+ });++ it('includes a summary derived from the payload when present', () => {+ const [member] = buildCastFromIngredients([+ { id: 'c1', name: 'Mara', type: 'character', payload: { physicalDescription: 'A tall figure in a grey coat.' } },+ ]);+ expect(member.summary).toContain('grey coat');+ });++ it('skips records without an id and caps at 50 members', () => {+ const many = Array.from({ length: 60 }, (_, i) => ({ id: `c${i}`, name: `N${i}`, type: 'character', payload: {} }));+ const cast = buildCastFromIngredients([{ name: 'no id', type: 'character', payload: {} }, ...many]);+ expect(cast).toHaveLength(50);+ expect(cast.every((m) => m.ingredientId)).toBe(true);+ });++ it('returns [] for non-array / empty input', () => {+ expect(buildCastFromIngredients(null)).toEqual([]);+ expect(buildCastFromIngredients(undefined)).toEqual([]);+ expect(buildCastFromIngredients([])).toEqual([]);+ });+});diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsindex 3370bdd661..770bc4f240 100644--- a/server/services/creativeDirector/local.js+++ b/server/services/creativeDirector/local.js@@ -24,6 +24,8 @@import { checkHealth, ensureSchema } from '../../lib/db.js';import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';+import { resolveIngredientsByIds, linkIngredientsToCreativeDirector } from '../catalogDB.js';+import { buildCastFromIngredients } from './catalogSeed.js';export { trimRuns, startingImageFilename } from './projectsLogic.js';@@ -93,8 +95,26 @@ export async function listProjectIds(options = {}) {}export async function createProject(input) {- const project = await (await selectBackend()).createProject(input);+ // Catalog "Remix into → Creative Director" handoff (#1808): resolve any seeded+ // ingredient ids to live records, fold them into the project as structured+ // `cast` (grounds the treatment prompt + per-scene casting), then link them+ // durably via catalog_ingredient_refs (ref_kind='creative-director') so the+ // Catalog "Appears in" panel and the convergence contract see one data model.+ // `catalogIngredientIds` is consumed here and never persisted on the record —+ // buildProjectRecord only reads named fields, so the raw id list drops out.+ const ingredients = await resolveIngredientsByIds(input.catalogIngredientIds);+ const seededInput = ingredients.length+ ? { ...input, cast: buildCastFromIngredients(ingredients) }+ : input;+ const project = await (await selectBackend()).createProject(seededInput);announceNewProject(project.id);+ if (ingredients.length > 0) {+ // Best-effort: the project is already created, so a ref-link failure must+ // not fail the request (mirrors storyBuilder's linkIngredientsToSeries).+ await linkIngredientsToCreativeDirector(project.id, ingredients)+ .then((linked) => console.log(`🎬 Linked ${linked.length} catalog ingredient(s) to Creative Director project ${project.id}`))+ .catch((err) => console.error(`❌ Failed to link catalog ingredients to CD project ${project.id}: ${err.message}`));+ }return project;}diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.jsindex 99fe4acf34..6da498df13 100644--- a/server/services/creativeDirector/local.test.js+++ b/server/services/creativeDirector/local.test.js@@ -17,6 +17,15 @@ vi.mock('../mediaCollections.js', () => ({createCollection: vi.fn(async () => ({ id: 'col-1' })),}));+// local.js imports catalogDB for the #1808 catalog-seed path; mock it so this+// dispatcher test doesn't pull in the real Postgres/instances/peer-sync chain+// (none of these cases pass catalogIngredientIds, so the resolve is a no-op).+vi.mock('../catalogDB.js', () => ({+ resolveIngredientsByIds: vi.fn(async () => []),+ linkIngredientsToCreativeDirector: vi.fn(async () => []),+ cdRefRoleForType: (type) => type,+}));+const { setTreatment, recordRun, updateRun, trimRuns } = await import('./local.js');const VALID_TREATMENT = {diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex 944e5e0b64..98a627c421 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -86,6 +86,7 @@ export function buildProjectRecord(input, { id, now, collectionId }) {name, aspectRatio, quality, modelId, targetDurationSeconds,styleSpec = '', startingImageFile = null, userStory = null,disableAudio = true, autoAcceptScenes = false, sourceIssueId = null,+ cast = [],} = input;return {id,@@ -100,6 +101,12 @@ export function buildProjectRecord(input, { id, now, collectionId }) {styleSpec,startingImageFile,userStory,+ // Catalog ingredients seeded into this project via the Catalog "Remix into+ // → Creative Director" handoff (#1808). Structured casting context the+ // treatment agent grounds the prompt + per-scene casting on; the same+ // ingredients are also linked durably in catalog_ingredient_refs. Empty for+ // a bare project. Each member: { ingredientId, name, type, role, summary? }.+ cast: Array.isArray(cast) ? cast : [],disableAudio,autoAcceptScenes,// Optional back-pointer to the pipeline issue that spawned this project.diff --git a/server/services/creativeDirector/projectsLogic.test.js b/server/services/creativeDirector/projectsLogic.test.jsindex b6bb471aac..155b58b208 100644--- a/server/services/creativeDirector/projectsLogic.test.js+++ b/server/services/creativeDirector/projectsLogic.test.js@@ -38,6 +38,28 @@ describe('buildProjectRecord', () => {timelineProjectId: null, finalVideoId: null, treatment: null, runs: [],});});++ it('defaults cast to [] and passes a supplied cast through (#1808)', () => {+ const bare = buildProjectRecord(+ { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9 },+ { id: 'cd-1', now: '2026-06-07T00:00:00.000Z', collectionId: 'col-1' },+ );+ expect(bare.cast).toEqual([]);++ const cast = [{ ingredientId: 'cat-c', name: 'Mara', type: 'character', role: 'cast' }];+ const seeded = buildProjectRecord(+ { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9, cast },+ { id: 'cd-2', now: '2026-06-07T00:00:00.000Z', collectionId: 'col-1' },+ );+ expect(seeded.cast).toEqual(cast);++ // A malformed (non-array) cast coerces to [] rather than persisting junk.+ const bad = buildProjectRecord(+ { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9, cast: 'nope' },+ { id: 'cd-3', now: '2026-06-07T00:00:00.000Z', collectionId: 'col-1' },+ );+ expect(bad.cast).toEqual([]);+ });});describe('applyProjectPatch', () => {@@ -70,6 +92,15 @@ describe('applyTreatment — status preservation', () => {it('throws on an invalid treatment', () => {expect(() => applyTreatment({ id: 'cd-1', status: 'planning' }, { logline: '', synopsis: '', scenes: [] })).toThrow(/Treatment validation failed/);});+ it('preserves per-scene cast the agent supplied (#1808)', () => {+ const sceneCast = [{ ingredientId: 'cat-c', name: 'Mara', role: 'cast' }];+ const treatment = {+ ...VALID_TREATMENT,+ scenes: [{ ...VALID_TREATMENT.scenes[0], cast: sceneCast }],+ };+ const next = applyTreatment({ id: 'cd-1', status: 'planning' }, treatment);+ expect(next.treatment.scenes[0].cast).toEqual(sceneCast);+ });});describe('applySceneUpdate', () => {diff --git a/server/services/creativeDirector/smokeTest.test.js b/server/services/creativeDirector/smokeTest.test.jsindex c07563f723..f55a59ba9d 100644--- a/server/services/creativeDirector/smokeTest.test.js+++ b/server/services/creativeDirector/smokeTest.test.js@@ -22,6 +22,15 @@ vi.mock('../../lib/mediaModels.js', () => ({getDefaultVideoModelId: () => 'ltx23_distilled_q4',}));+// createProject (via local.js) now imports catalogDB for the #1808 catalog-seed+// path; mock it so the smoke test doesn't pull in the real Postgres/instances/+// peer-sync chain (the smoke project passes no catalogIngredientIds).+vi.mock('../catalogDB.js', () => ({+ resolveIngredientsByIds: vi.fn(async () => []),+ linkIngredientsToCreativeDirector: vi.fn(async () => []),+ cdRefRoleForType: (type) => type,+}));+const { createSmokeTestProject } = await import('./smokeTest.js');beforeEach(() => {diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex 8d6fdef44d..671d964ed5 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -46,7 +46,7 @@ import {} from '../lib/storyBuilderSteps.js';import { hashUpstream, computeStaleSteps, computeSyncDrift } from '../lib/storyBuilderIntegrity.js';import { getStoryBuilderStore } from './storyBuilderStore/store.js';-import { listIngredients, linkIngredientsToSeries } from './catalogDB.js';+import { linkIngredientsToSeries, resolveIngredientsByIds } from './catalogDB.js';import { getActiveCatalogType, payloadSnippet } from '../lib/catalogTypes.js';import { createUniverse, deleteUniverse, getUniverse, updateUniverse } from './universeBuilder.js';import { expandWorldTemplate } from './universeBuilderExpand.js';@@ -117,21 +117,11 @@ function composeSeedFromIngredients(ingredients) {return `${composed.slice(0, SEED_MAX - 1)}…`;}-// Resolve the selected catalog ingredient ids to live ingredient records in a-// single batch query (`listIngredients({ ids })` already excludes soft-deleted-// rows), then re-order to the caller's pick order so the composed seed reads in-// the order the user selected. Missing/deleted ids are simply absent and skipped.-async function resolveCatalogIngredients(ids) {- // De-dupe so a direct API caller passing the same id twice doesn't double the- // seed bullet (the UI selects via a Set, so this is only reachable off-UI).- const list = [...new Set((Array.isArray(ids) ? ids : [])- .filter((id) => isStr(id) && id.trim())- .map((id) => id.trim()))];- if (list.length === 0) return [];- const { items } = await listIngredients({ ids: list, limit: list.length });- const byId = new Map(items.map((ing) => [ing.id, ing]));- return list.map((id) => byId.get(id)).filter(Boolean);-}+// Resolve the selected catalog ingredient ids to live ingredient records+// (de-duped, pick-order-preserving, soft-deleted excluded). Delegates to the+// shared catalogDB resolver (#1808) so Story Builder and Creative Director share+// one implementation instead of each carrying its own copy.+const resolveCatalogIngredients = (ids) => resolveIngredientsByIds(ids);// Steps the importer actually pre-fills, so they open "ready" for review on an// import-mode session. `idea` (universe + series exist), `plotArc` (arc +diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.jsindex 3fca7e8315..0dbc689ab3 100644--- a/server/services/storyBuilder.test.js+++ b/server/services/storyBuilder.test.js@@ -33,10 +33,27 @@ vi.mock('../lib/stageRunner.js', () => ({// real DB (#1761). listIngredients (the batch resolve) and linkIngredientsToSeries// (the batch link) are spies the tests program per case; the type→role vocabulary// itself is covered in catalogDB.test.js.-const catalogMocks = vi.hoisted(() => ({- listIngredients: vi.fn(),- linkIngredientsToSeries: vi.fn(),-}));+const catalogMocks = vi.hoisted(() => {+ const listIngredients = vi.fn();+ return {+ listIngredients,+ linkIngredientsToSeries: vi.fn(),+ // resolveIngredientsByIds is the shared resolver storyBuilder now delegates+ // to (#1808). Mirror the real dedupe + pick-order logic but route the batch+ // fetch through the mocked listIngredients so every existing per-case+ // `listIngredients.mockResolvedValue(...)` + call-args assertion still drives+ // it unchanged.+ resolveIngredientsByIds: vi.fn(async (ids) => {+ const list = [...new Set((Array.isArray(ids) ? ids : [])+ .filter((id) => typeof id === 'string' && id.trim())+ .map((id) => id.trim()))];+ if (list.length === 0) return [];+ const { items } = await listIngredients({ ids: list, limit: list.length });+ const byId = new Map((items || []).map((ing) => [ing.id, ing]));+ return list.map((id) => byId.get(id)).filter(Boolean);+ }),+ };+});vi.mock('./catalogDB.js', () => catalogMocks);const sb = await import('./storyBuilder.js');