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
[issue-1810] Auto-cast: director pulls catalog ingredients into a CD project
Adam Eivy5d613c1f8fb0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 54e72385f2..bc430c1b99 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,7 @@## Creative Director+- **[issue-1810] Auto-cast a project from its brief — let the director pull catalog ingredients for you.** The Overview tab gains an **Auto-cast** button: instead of hand-picking each character/place/object/scene to remix in, the Creative Director reads the project's brief (style spec + story) and searches your whole Catalog — the same hybrid full-text + semantic (pgvector) search the Ask retriever uses — to find the best-matching ingredients, then **appends** them to the project cast and links them back so each shows up in its Catalog "Appears in" list. It only adds new matches (never replaces what you've already cast), everything it adds is editable, and the button stays disabled until the project has a style spec or story to search from. This is the autonomous "Auto-generate" slice of the creative pipeline; auto-composing a full treatment from the cast and chaining first-pass image/video/music gen are tracked as follow-ups. (Closes #1810)- **[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 modediff --git a/client/src/components/creative-director/OverviewTab.jsx b/client/src/components/creative-director/OverviewTab.jsxindex 07b8ce984a..3fbf10fd70 100644--- a/client/src/components/creative-director/OverviewTab.jsx+++ b/client/src/components/creative-director/OverviewTab.jsx@@ -1,11 +1,13 @@import { Link } from 'react-router-dom';import { useState, useEffect, useRef } from 'react';-import { updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';+import { Sparkles, Loader2 } from 'lucide-react';+import { updateCreativeDirectorProject, applyCreativeDirectorAutoCast } from '../../services/apiCreativeDirector.js';import toast from '../ui/Toast';export default function OverviewTab({ project, onProjectUpdate }) {const [disableAudio, setDisableAudio] = useState(project.disableAudio === true);const [saving, setSaving] = useState(false);+ const [autoCasting, setAutoCasting] = useState(false);// Track the project id this tab is currently mounted for. If the user// toggles audio and navigates to a different CD project before the PATCH// resolves, the late `.then()` would otherwise call onProjectUpdate on@@ -56,6 +58,26 @@ export default function OverviewTab({ project, onProjectUpdate }) {}});};+ // Autonomous auto-cast (#1810): the director queries the catalog from the+ // project's brief and APPENDS the fresh matches to the cast. Guarded against a+ // project switch mid-request so the result lands on the project that asked.+ const handleAutoCast = () => {+ setAutoCasting(true);+ const requestProjectId = project.id;+ applyCreativeDirectorAutoCast(requestProjectId, {}, { silent: true })+ .then((result) => {+ if (projectIdRef.current !== requestProjectId) return;+ const added = result?.added?.length || 0;+ onProjectUpdate?.({ cast: result?.project?.cast || [] });+ if (added > 0) toast.success(`Auto-cast added ${added} ingredient${added === 1 ? '' : 's'}`);+ else toast.info('Auto-cast found no new catalog matches for this brief');+ })+ .catch((err) => toast.error(err.message || 'Auto-cast failed'))+ .finally(() => {+ if (projectIdRef.current === requestProjectId) setAutoCasting(false);+ });+ };+const collectionLink = `/media/collections/${project.collectionId}`;const final = project.finalVideoId? <Link to={`/media/history?selected=${project.finalVideoId}`} className="text-port-accent">{project.finalVideoId}</Link>@@ -109,14 +131,32 @@ export default function OverviewTab({ project, onProjectUpdate }) {</section>)}- {Array.isArray(project.cast) && project.cast.length > 0 && (- <section className="bg-port-card border border-port-border rounded p-4">- <h2 className="text-sm font-semibold text-port-text-muted uppercase tracking-wide mb-2">- Cast ({project.cast.length})+ <section className="bg-port-card border border-port-border rounded p-4">+ <div className="flex items-center justify-between mb-2">+ <h2 className="text-sm font-semibold text-port-text-muted uppercase tracking-wide">+ Cast ({Array.isArray(project.cast) ? project.cast.length : 0})</h2>- <p className="text-xs text-port-text-muted mb-2">- Catalog ingredients remixed into this project — the director grounds the treatment and per-scene casting on them.- </p>+ {/* Autonomous auto-cast (#1810): seed the cast from the catalog without+ hand-picking. Disabled with no brief to search on. */}+ <button+ type="button"+ onClick={handleAutoCast}+ disabled={autoCasting || !hasSearchableBrief(project)}+ title={hasSearchableBrief(project)+ ? 'Let the director pick catalog ingredients from this project’s brief'+ : 'Add a style spec or story first — auto-cast searches the catalog from the project brief'}+ className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-port-text hover:border-port-accent disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {autoCasting+ ? <Loader2 size={12} className="animate-spin" aria-hidden="true" />+ : <Sparkles size={12} aria-hidden="true" />}+ {autoCasting ? 'Auto-casting…' : 'Auto-cast'}+ </button>+ </div>+ <p className="text-xs text-port-text-muted mb-2">+ Catalog ingredients remixed into this project — the director grounds the treatment and per-scene casting on them. Auto-cast appends new matches; you can always edit the result.+ </p>+ {Array.isArray(project.cast) && project.cast.length > 0 ? (<div className="flex flex-col gap-1.5">{project.cast.map((member) => {// Ingredient detail route is /catalog/:type/:id (matches CatalogCard);@@ -137,8 +177,12 @@ export default function OverviewTab({ project, onProjectUpdate }) {);})}</div>- </section>- )}+ ) : (+ <p className="text-sm text-port-text-muted italic">+ No cast yet — use Auto-cast to pull matching catalog ingredients, or remix them in from the Catalog.+ </p>+ )}+ </section>{project.failureReason && (<section className="bg-port-card border border-port-error rounded p-4">@@ -150,6 +194,17 @@ export default function OverviewTab({ project, onProjectUpdate }) {);}+// True when the project carries enough authored brief (style spec or user story)+// to be worth an auto-cast search. The server also folds in the project name, but+// a name alone is low signal — so the UI only offers auto-cast once there's a real+// brief to match catalog ingredients against.+function hasSearchableBrief(project) {+ return Boolean(+ (typeof project?.styleSpec === 'string' && project.styleSpec.trim())+ || (typeof project?.userStory === 'string' && project.userStory.trim()),+ );+}+function Field({ label, value }) {return (<div className="grid grid-cols-3 gap-2 text-sm">diff --git a/client/src/components/creative-director/OverviewTab.test.jsx b/client/src/components/creative-director/OverviewTab.test.jsxnew file mode 100644index 0000000000..e929265564--- /dev/null+++ b/client/src/components/creative-director/OverviewTab.test.jsx@@ -0,0 +1,86 @@+/**+ * Tests for the Overview tab's autonomous auto-cast affordance (#1810):+ * the button gates on a searchable brief, appends returned cast on success,+ * and renders an empty-state when the project has no cast yet.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++vi.mock('../../services/apiCreativeDirector.js', () => ({+ updateCreativeDirectorProject: vi.fn(async () => ({})),+ applyCreativeDirectorAutoCast: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));++import OverviewTab from './OverviewTab.jsx';+import { applyCreativeDirectorAutoCast } from '../../services/apiCreativeDirector.js';+import toast from '../ui/Toast';++const baseProject = {+ id: 'cd-1', name: 'Neon Run', aspectRatio: '16:9', quality: 'standard',+ modelId: 'm1', targetDurationSeconds: 30, collectionId: 'col-1',+ styleSpec: 'rain noir', userStory: null, cast: [],+};++const renderTab = (project, onProjectUpdate = () => {}) =>+ render(<MemoryRouter><OverviewTab project={project} onProjectUpdate={onProjectUpdate} /></MemoryRouter>);++beforeEach(() => { vi.clearAllMocks(); });++describe('OverviewTab auto-cast (#1810)', () => {+ it('shows the empty-state when the project has no cast', () => {+ renderTab(baseProject);+ expect(screen.getByText(/No cast yet/i)).toBeTruthy();+ expect(screen.getByText('Cast (0)')).toBeTruthy();+ });++ it('disables Auto-cast when there is no style spec or story', () => {+ renderTab({ ...baseProject, styleSpec: '', userStory: '' });+ expect(screen.getByRole('button', { name: /Auto-cast/i })).toHaveProperty('disabled', true);+ });++ it('enables Auto-cast when a style spec is present', () => {+ renderTab(baseProject);+ expect(screen.getByRole('button', { name: /^Auto-cast$/i })).toHaveProperty('disabled', false);+ });++ it('enables Auto-cast when only a user story is present', () => {+ renderTab({ ...baseProject, styleSpec: '', userStory: 'a courier flees the city' });+ expect(screen.getByRole('button', { name: /^Auto-cast$/i })).toHaveProperty('disabled', false);+ });++ it('applies auto-cast and pushes the returned cast up on success', async () => {+ const onProjectUpdate = vi.fn();+ applyCreativeDirectorAutoCast.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1', name: 'The Spire', type: 'place', role: 'location' }] },+ added: [{ ingredientId: 'p1', name: 'The Spire' }],+ suggestions: [],+ });+ renderTab(baseProject, onProjectUpdate);++ fireEvent.click(screen.getByRole('button', { name: /^Auto-cast$/i }));++ await waitFor(() => expect(applyCreativeDirectorAutoCast).toHaveBeenCalledWith('cd-1', {}, { silent: true }));+ await waitFor(() => expect(onProjectUpdate).toHaveBeenCalledWith({+ cast: [{ ingredientId: 'p1', name: 'The Spire', type: 'place', role: 'location' }],+ }));+ expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/added 1 ingredient/i));+ });++ it('toasts an info message when nothing new matched', async () => {+ applyCreativeDirectorAutoCast.mockResolvedValue({ project: { id: 'cd-1', cast: [] }, added: [], suggestions: [] });+ renderTab(baseProject);+ fireEvent.click(screen.getByRole('button', { name: /^Auto-cast$/i }));+ await waitFor(() => expect(toast.info).toHaveBeenCalledWith(expect.stringMatching(/no new catalog matches/i)));+ });++ it('toasts an error and recovers when auto-cast fails', async () => {+ applyCreativeDirectorAutoCast.mockRejectedValue(new Error('boom'));+ renderTab(baseProject);+ fireEvent.click(screen.getByRole('button', { name: /^Auto-cast$/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('boom'));+ // button re-enables after the failure+ await waitFor(() => expect(screen.getByRole('button', { name: /^Auto-cast$/i })).toHaveProperty('disabled', false));+ });+});diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.jsindex b52a27f737..730d57984b 100644--- a/client/src/services/apiCreativeDirector.js+++ b/client/src/services/apiCreativeDirector.js@@ -30,3 +30,25 @@ export const resumeCreativeDirectorProject = (id) => request(`/creative-directorexport const createSmokeTestCreativeDirectorProject = () => request('/creative-director/smoke-test', {method: 'POST',});+// Autonomous auto-cast (#1810). `suggest` previews the catalog ingredients the+// director would propose for a free-text brief (no mutation). `apply` derives the+// brief from the project (or accepts an explicit one), appends the fresh+// candidates to the project cast, and links them — returning+// `{ project, added, suggestions }`. `options.silent` defers error toasting to a+// caller that owns its own error UI.+export const suggestCreativeDirectorAutoCast = (brief, { types, limit } = {}, options = {}) =>+ request('/creative-director/auto-cast/suggest', {+ method: 'POST',+ body: JSON.stringify({ brief, ...(types ? { types } : {}), ...(limit ? { limit } : {}) }),+ ...options,+ });+export const applyCreativeDirectorAutoCast = (id, { brief, types, limit } = {}, options = {}) =>+ request(`/creative-director/${encodeURIComponent(id)}/auto-cast`, {+ method: 'POST',+ body: JSON.stringify({+ ...(brief ? { brief } : {}),+ ...(types ? { types } : {}),+ ...(limit ? { limit } : {}),+ }),+ ...options,+ });diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex eac3ccd035..52396d2e03 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -78,6 +78,26 @@ export const creativeDirectorProjectCreateSchema = z.object({sourceIssueId: z.string().min(1).max(64).nullable().optional(),});+// Autonomous auto-cast (#1810). `types` narrows the catalog search to a set of+// castable atom types (default character/place/object/scene server-side); `limit`+// caps how many candidates the hybrid search returns. The suggest variant needs a+// brief to search on; the apply variant derives one from the project when omitted.+const autoCastTypes = z.array(z.string().trim().min(1).max(64)).max(10).optional();+const autoCastLimit = z.number().int().min(1).max(50).optional();++export const creativeDirectorAutoCastSuggestSchema = z.object({+ brief: z.string().min(1).max(10000),+ types: autoCastTypes,+ limit: autoCastLimit,+});++export const creativeDirectorAutoCastApplySchema = z.object({+ // Omitted → the service derives the brief from the project's name/style/story.+ brief: z.string().max(10000).optional(),+ types: autoCastTypes,+ limit: autoCastLimit,+});+// Update is restricted to a few editable fields. modelId / aspectRatio /// quality / targetDurationSeconds are locked at creation — changing them// mid-project would invalidate already-rendered segments.diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex bcd0b2ecd6..e3171a9f6c 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -15,6 +15,8 @@ import {creativeDirectorProjectUpdateSchema,creativeDirectorTreatmentSchema,creativeDirectorSceneUpdateSchema,+ creativeDirectorAutoCastSuggestSchema,+ creativeDirectorAutoCastApplySchema,} from '../lib/validation.js';import {listProjects,@@ -25,6 +27,7 @@ import {setTreatment,updateScene,} from '../services/creativeDirector/local.js';+import { suggestCastForBrief, applyAutoCastToProject, toSuggestionView } from '../services/creativeDirector/autoCast.js';import { startCreativeDirectorProject } from '../services/creativeDirector/completionHook.js';import { createSmokeTestProject } from '../services/creativeDirector/smokeTest.js';@@ -69,6 +72,16 @@ router.post('/', asyncHandler(async (req, res) => {res.status(201).json(project);}));+// Autonomous auto-cast (#1810) — preview only: given a free-text brief, return the+// catalog ingredients the director would propose (hybrid FTS + pgvector search),+// without mutating anything. Registered before `/:id/auto-cast` so the literal+// path can't be shadowed by the param route.+router.post('/auto-cast/suggest', asyncHandler(async (req, res) => {+ const { brief, types, limit } = validateRequest(creativeDirectorAutoCastSuggestSchema, req.body);+ const hits = await suggestCastForBrief({ brief, types, limit });+ res.json({ suggestions: hits.map(toSuggestionView).filter(Boolean) });+}));+router.patch('/:id', asyncHandler(async (req, res) => {const data = validateRequest(creativeDirectorProjectUpdateSchema, req.body);const updated = await updateProject(req.params.id, data);@@ -80,6 +93,16 @@ router.delete('/:id', asyncHandler(async (req, res) => {res.json({ ok: true });}));+// Autonomous auto-cast (#1810) — apply to a project: derive a brief from the+// project (or accept an explicit one), search the catalog, APPEND the fresh+// candidates to the project cast, and link them as creative-director refs.+// Returns the updated project plus what was added/considered.+router.post('/:id/auto-cast', asyncHandler(async (req, res) => {+ const { brief, types, limit } = validateRequest(creativeDirectorAutoCastApplySchema, req.body);+ const result = await applyAutoCastToProject(req.params.id, { brief, types, limit });+ res.json(result);+}));+// Agent-callable: write the treatment doc.router.patch('/:id/treatment', asyncHandler(async (req, res) => {const treatment = validateRequest(creativeDirectorTreatmentSchema, req.body);diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex fb043ea5f7..8ff15b519c 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -17,7 +17,16 @@ vi.mock('../services/creativeDirector/completionHook.js', () => ({advanceAfterSceneSettled: vi.fn(async () => undefined),}));+// Mock the auto-cast service so the route test doesn't pull the real+// catalogDB/embeddings graph; the route's job here is to validate + dispatch.+vi.mock('../services/creativeDirector/autoCast.js', () => ({+ suggestCastForBrief: vi.fn(async () => [{ ingredient: { id: 'c1', type: 'character', name: 'Mara', payload: {} }, rrfScore: 0.5, searchMethod: 'hybrid' }]),+ applyAutoCastToProject: vi.fn(async () => ({ project: { id: 'cd-1', cast: [] }, added: [], suggestions: [] })),+ toSuggestionView: (hit) => ({ ingredientId: hit.ingredient.id, name: hit.ingredient.name, type: hit.ingredient.type, score: hit.rrfScore, searchMethod: hit.searchMethod }),+}));+import * as cdService from '../services/creativeDirector/local.js';+import * as autoCast from '../services/creativeDirector/autoCast.js';import * as hook from '../services/creativeDirector/completionHook.js';import creativeDirectorRoutes from './creativeDirector.js';@@ -241,4 +250,47 @@ describe('creativeDirector routes', () => {expect(hook.advanceAfterSceneSettled).toHaveBeenCalledWith('cd-1');});});++ describe('POST /auto-cast/suggest (#1810)', () => {+ it('400s when brief is missing', async () => {+ const r = await request(app).post('/api/creative-director/auto-cast/suggest').send({});+ expect(r.status).toBe(400);+ expect(autoCast.suggestCastForBrief).not.toHaveBeenCalled();+ });++ it('returns slimmed suggestions for a brief (no full ingredient leak)', async () => {+ const r = await request(app).post('/api/creative-director/auto-cast/suggest').send({ brief: 'rain noir' });+ expect(r.status).toBe(200);+ expect(autoCast.suggestCastForBrief).toHaveBeenCalledWith({ brief: 'rain noir', types: undefined, limit: undefined });+ expect(r.body.suggestions).toEqual([+ { ingredientId: 'c1', name: 'Mara', type: 'character', score: 0.5, searchMethod: 'hybrid' },+ ]);+ expect(r.body.suggestions[0]).not.toHaveProperty('payload');+ });++ it('is not shadowed by the /:id param route', async () => {+ // /auto-cast/suggest must hit the literal handler, not POST /:id/auto-cast+ const r = await request(app).post('/api/creative-director/auto-cast/suggest').send({ brief: 'x' });+ expect(r.status).toBe(200);+ expect(autoCast.applyAutoCastToProject).not.toHaveBeenCalled();+ });+ });++ describe('POST /:id/auto-cast (#1810)', () => {+ it('applies auto-cast to the project and returns the result', async () => {+ autoCast.applyAutoCastToProject.mockResolvedValue({+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],+ });+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ limit: 5 });+ expect(r.status).toBe(200);+ expect(autoCast.applyAutoCastToProject).toHaveBeenCalledWith('cd-1', { brief: undefined, types: undefined, limit: 5 });+ expect(r.body.added).toEqual([{ ingredientId: 'p1' }]);+ });++ it('400s on an over-cap limit', async () => {+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ limit: 999 });+ expect(r.status).toBe(400);+ expect(autoCast.applyAutoCastToProject).not.toHaveBeenCalled();+ });+ });});diff --git a/server/services/creativeDirector/autoCast.js b/server/services/creativeDirector/autoCast.jsnew file mode 100644index 0000000000..8f5b0b87d4--- /dev/null+++ b/server/services/creativeDirector/autoCast.js@@ -0,0 +1,135 @@+/**+ * Creative Director — autonomous catalog auto-cast (#1810).+ *+ * The "Auto-generate" slice of the creative-pipeline epic (#1721). Instead of the+ * user hand-picking each catalog ingredient to remix into a Creative Director+ * project, the director queries the catalog itself — embedding the project's brief+ * and running the SAME hybrid (FTS + pgvector) search the Ask retriever uses — to+ * propose castable ingredients, then seeds them as the project `cast` and links+ * them via catalog_ingredient_refs (ref_kind='creative-director'), exactly like+ * the manual remix path (#1808).+ *+ * Director-first principle (mirrors the Music-video slice): autonomy SEEDS the+ * board, the director can always take over — everything auto-cast adds is editable+ * on the same project, and the apply path only ever appends (never replaces) the+ * existing cast.+ *+ * Convergence contract: the autonomous path references the same Catalog ingredients+ * through the same refs as the manual remix — no parallel data model.+ */++import {+ hybridSearchIngredients,+ linkIngredientsToCreativeDirector,+} from '../catalogDB.js';+import { generateQueryEmbedding } from '../memoryEmbeddings.js';+import { buildCastFromIngredients } from './catalogSeed.js';+import { getProject, updateProject } from './local.js';+import { ServerError } from '../../lib/errorHandler.js';++// The catalog atom types that make sense as a director's "cast" — the on-screen+// subjects a treatment binds to scenes. Ideas/concepts are context, not cast, so+// they're excluded by default; a caller may override `types` to widen the net.+export const DEFAULT_CASTABLE_TYPES = ['character', 'place', 'object', 'scene'];+// Mirror catalogSeed's MAX_CAST and the create-schema `catalogIngredientIds` cap —+// past ~50 members the treatment agent can't reason about per-scene casting.+const MAX_CAST = 50;+const BRIEF_MAX = 8000;+const DEFAULT_SUGGEST_LIMIT = 12;++/**+ * Pure: assemble a search brief from a project's authored fields. Name + style+ * spec + user story are the human's stated intent; joining them gives the+ * embedding/FTS query something to match catalog ingredients against. Returns ''+ * when the project carries no usable text (the caller decides what to do).+ */+export function deriveBriefFromProject(project) {+ if (!project || typeof project !== 'object') return '';+ const brief = [project.name, project.styleSpec, project.userStory]+ .filter((v) => typeof v === 'string' && v.trim())+ .map((v) => v.trim())+ .join('\n\n');+ return brief.length > BRIEF_MAX ? brief.slice(0, BRIEF_MAX) : brief;+}++/**+ * Slim a hybrid-search hit to the fields the suggest UI needs — never leak the+ * full payload/embedding. Reuses buildCastFromIngredients so the summary/role+ * derivation matches what an applied cast member carries, then layers the search+ * score + method on top.+ */+export function toSuggestionView(hit) {+ const [member] = buildCastFromIngredients([hit.ingredient]);+ if (!member) return null;+ return {+ ...member,+ score: typeof hit.rrfScore === 'number' ? hit.rrfScore : null,+ searchMethod: hit.searchMethod || 'fts',+ };+}++/**+ * Run the autonomous selection: embed the brief, hybrid-search the catalog, and+ * return the ranked castable hits (raw `{ ingredient, rrfScore, searchMethod }`).+ * The embedding is best-effort — if the embedding provider is unavailable the+ * search degrades to FTS-only rather than failing (mirrors askService).+ */+export async function suggestCastForBrief({ brief, types = DEFAULT_CASTABLE_TYPES, limit = DEFAULT_SUGGEST_LIMIT } = {}) {+ const text = (typeof brief === 'string' ? brief : '').trim();+ if (!text) return [];+ const castable = Array.isArray(types) && types.length ? types : DEFAULT_CASTABLE_TYPES;+ const embedding = await generateQueryEmbedding(text, { types: castable }).catch(() => null);+ // hybridSearchIngredients filters by a single `type`; fetch a wider unfiltered+ // page and post-filter to the castable set so multiple types work in one query.+ const hits = await hybridSearchIngredients(text, embedding, { limit: limit * 3 });+ const allowed = new Set(castable);+ return hits.filter((h) => allowed.has(h.ingredient?.type)).slice(0, limit);+}++/**+ * Apply auto-cast to an existing project: derive (or accept) a brief, suggest+ * castable ingredients, APPEND the fresh ones (those not already cast) to the+ * project `cast`, and link them as creative-director refs. Returns the updated+ * project, the members actually added, and the full ranked suggestions (so the UI+ * can show what was considered, including already-cast matches).+ */+export async function applyAutoCastToProject(projectId, { brief, types, limit } = {}) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });++ const effectiveBrief = (typeof brief === 'string' && brief.trim())+ ? brief.trim()+ : deriveBriefFromProject(project);+ if (!effectiveBrief) {+ throw new ServerError(+ 'Nothing to auto-cast from — give the project a style spec or story, or pass a brief.',+ { status: 400, code: 'NO_BRIEF' },+ );+ }++ const hits = await suggestCastForBrief({ brief: effectiveBrief, types, limit });+ const suggestions = hits.map(toSuggestionView).filter(Boolean);++ const existingCast = Array.isArray(project.cast) ? project.cast : [];+ const existingIds = new Set(existingCast.map((c) => c.ingredientId));+ const capacity = Math.max(0, MAX_CAST - existingCast.length);+ const freshIngredients = hits+ .map((h) => h.ingredient)+ .filter((ing) => ing?.id && !existingIds.has(ing.id))+ .slice(0, capacity);++ if (freshIngredients.length === 0) {+ return { project, added: [], suggestions };+ }++ const newMembers = buildCastFromIngredients(freshIngredients);+ const mergedCast = [...existingCast, ...newMembers];+ const updated = await updateProject(projectId, { cast: mergedCast });++ // Best-effort ref-link (the cast is already persisted) — mirrors createProject.+ await linkIngredientsToCreativeDirector(projectId, freshIngredients)+ .then((linked) => console.log(`🎬 Auto-cast linked ${linked.length} ingredient(s) to CD project ${projectId}`))+ .catch((err) => console.error(`❌ Auto-cast ref-link failed for CD project ${projectId}: ${err.message}`));++ return { project: updated, added: newMembers, suggestions };+}diff --git a/server/services/creativeDirector/autoCast.test.js b/server/services/creativeDirector/autoCast.test.jsnew file mode 100644index 0000000000..9e1f1dad6f--- /dev/null+++ b/server/services/creativeDirector/autoCast.test.js@@ -0,0 +1,177 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the I/O boundaries; keep catalogSeed + catalogTypes real (pure transforms).+// The catalogDB mock must still provide cdRefRoleForType because the real+// catalogSeed imports it for role mapping.+vi.mock('../catalogDB.js', () => ({+ hybridSearchIngredients: vi.fn(),+ linkIngredientsToCreativeDirector: vi.fn(async () => []),+ cdRefRoleForType: (type) => ({ character: 'cast', place: 'location', object: 'prop', scene: 'scene' }[type] || 'reference'),+}));+vi.mock('../memoryEmbeddings.js', () => ({+ generateQueryEmbedding: vi.fn(async () => [0.1, 0.2, 0.3]),+}));+vi.mock('./local.js', () => ({+ getProject: vi.fn(),+ updateProject: vi.fn(),+}));++import {+ deriveBriefFromProject,+ suggestCastForBrief,+ applyAutoCastToProject,+ toSuggestionView,+ DEFAULT_CASTABLE_TYPES,+} from './autoCast.js';+import { hybridSearchIngredients, linkIngredientsToCreativeDirector } from '../catalogDB.js';+import { generateQueryEmbedding } from '../memoryEmbeddings.js';+import { getProject, updateProject } from './local.js';++const hit = (id, type, name, rrfScore = 0.5, searchMethod = 'hybrid') => ({+ ingredient: { id, type, name, payload: {} },+ rrfScore,+ searchMethod,+});++beforeEach(() => {+ vi.clearAllMocks();+ generateQueryEmbedding.mockResolvedValue([0.1, 0.2, 0.3]);+ linkIngredientsToCreativeDirector.mockResolvedValue([]);+});++describe('deriveBriefFromProject', () => {+ it('joins name + style spec + user story', () => {+ expect(deriveBriefFromProject({ name: 'Neon Run', styleSpec: 'rain noir', userStory: 'a courier flees' }))+ .toBe('Neon Run\n\nrain noir\n\na courier flees');+ });++ it('skips missing / blank fields', () => {+ expect(deriveBriefFromProject({ name: 'Neon Run', styleSpec: ' ', userStory: null }))+ .toBe('Neon Run');+ });++ it('returns "" for a null or empty project', () => {+ expect(deriveBriefFromProject(null)).toBe('');+ expect(deriveBriefFromProject({})).toBe('');+ });++ it('caps an overly long brief', () => {+ const brief = deriveBriefFromProject({ name: 'x'.repeat(9000) });+ expect(brief.length).toBeLessThanOrEqual(8000);+ });+});++describe('suggestCastForBrief', () => {+ it('returns [] for an empty brief without searching', async () => {+ expect(await suggestCastForBrief({ brief: ' ' })).toEqual([]);+ expect(hybridSearchIngredients).not.toHaveBeenCalled();+ });++ it('filters hits to the castable types and slices to the limit', async () => {+ hybridSearchIngredients.mockResolvedValue([+ hit('c1', 'character', 'Mara'),+ hit('i1', 'idea', 'A loose notion'), // not castable by default → dropped+ hit('p1', 'place', 'The Spire'),+ hit('x1', 'concept', 'Theme'), // not castable → dropped+ ]);+ const out = await suggestCastForBrief({ brief: 'rain noir', limit: 5 });+ expect(out.map((h) => h.ingredient.id)).toEqual(['c1', 'p1']);+ });++ it('respects an explicit types override', async () => {+ hybridSearchIngredients.mockResolvedValue([hit('c1', 'character', 'Mara'), hit('i1', 'idea', 'Notion')]);+ const out = await suggestCastForBrief({ brief: 'x', types: ['idea'] });+ expect(out.map((h) => h.ingredient.id)).toEqual(['i1']);+ });++ it('degrades to FTS-only when the embedding provider fails', async () => {+ generateQueryEmbedding.mockRejectedValue(new Error('no provider'));+ hybridSearchIngredients.mockResolvedValue([hit('c1', 'character', 'Mara')]);+ const out = await suggestCastForBrief({ brief: 'rain noir' });+ expect(out).toHaveLength(1);+ // embedding arg is null when the provider failed+ expect(hybridSearchIngredients).toHaveBeenCalledWith('rain noir', null, expect.any(Object));+ });++ it('defaults to the castable type set', () => {+ expect(DEFAULT_CASTABLE_TYPES).toContain('character');+ expect(DEFAULT_CASTABLE_TYPES).not.toContain('idea');+ });+});++describe('toSuggestionView', () => {+ it('slims a hit to the cast-member shape + score + method', () => {+ const view = toSuggestionView(hit('c1', 'character', 'Mara', 0.73, 'vector'));+ expect(view).toMatchObject({ ingredientId: 'c1', name: 'Mara', type: 'character', role: 'cast', score: 0.73, searchMethod: 'vector' });+ expect(view).not.toHaveProperty('payload'); // no full ingredient leak+ });+});++describe('applyAutoCastToProject', () => {+ it('404s when the project is missing', async () => {+ getProject.mockResolvedValue(null);+ await expect(applyAutoCastToProject('missing', {})).rejects.toMatchObject({ status: 404 });+ });++ it('400s (NO_BRIEF) when the project and request carry no brief', async () => {+ getProject.mockResolvedValue({ id: 'p1', name: '', styleSpec: '', userStory: '' });+ await expect(applyAutoCastToProject('p1', {})).rejects.toMatchObject({ status: 400, code: 'NO_BRIEF' });+ expect(hybridSearchIngredients).not.toHaveBeenCalled();+ });++ it('appends fresh members, dedupes against existing cast, and links refs', async () => {+ getProject.mockResolvedValue({+ id: 'p1', name: 'Neon Run', styleSpec: 'rain noir', userStory: null,+ cast: [{ ingredientId: 'c1', name: 'Mara', type: 'character', role: 'cast' }],+ });+ hybridSearchIngredients.mockResolvedValue([+ hit('c1', 'character', 'Mara'), // already cast → skipped+ hit('p1', 'place', 'The Spire'), // fresh → added+ ]);+ updateProject.mockImplementation(async (_id, patch) => ({ id: 'p1', ...patch }));++ const result = await applyAutoCastToProject('p1', {});+ expect(result.added.map((m) => m.ingredientId)).toEqual(['p1']);+ // cast persisted = existing + fresh+ expect(updateProject).toHaveBeenCalledWith('p1', { cast: expect.arrayContaining([+ expect.objectContaining({ ingredientId: 'c1' }),+ expect.objectContaining({ ingredientId: 'p1' }),+ ]) });+ // refs linked only for the fresh ingredient+ expect(linkIngredientsToCreativeDirector).toHaveBeenCalledWith('p1', [expect.objectContaining({ id: 'p1' })]);+ // suggestions include both (already-cast match still surfaced)+ expect(result.suggestions.map((s) => s.ingredientId).sort()).toEqual(['c1', 'p1']);+ });++ it('no-ops the write when every match is already cast', async () => {+ getProject.mockResolvedValue({+ id: 'p1', name: 'Neon Run', styleSpec: 'rain noir',+ cast: [{ ingredientId: 'c1', name: 'Mara', type: 'character', role: 'cast' }],+ });+ hybridSearchIngredients.mockResolvedValue([hit('c1', 'character', 'Mara')]);+ const result = await applyAutoCastToProject('p1', {});+ expect(result.added).toEqual([]);+ expect(updateProject).not.toHaveBeenCalled();+ expect(linkIngredientsToCreativeDirector).not.toHaveBeenCalled();+ });++ it('uses an explicit brief over the project-derived one', async () => {+ getProject.mockResolvedValue({ id: 'p1', name: 'Neon Run', styleSpec: 'rain noir', cast: [] });+ hybridSearchIngredients.mockResolvedValue([]);+ await applyAutoCastToProject('p1', { brief: 'sunlit meadow' });+ expect(hybridSearchIngredients).toHaveBeenCalledWith('sunlit meadow', expect.anything(), expect.any(Object));+ });++ it('caps the merged cast at 50 members', async () => {+ const existing = Array.from({ length: 49 }, (_, i) => ({ ingredientId: `e${i}`, name: `E${i}`, type: 'character', role: 'cast' }));+ getProject.mockResolvedValue({ id: 'p1', name: 'Neon Run', styleSpec: 'rain noir', cast: existing });+ hybridSearchIngredients.mockResolvedValue([+ hit('n1', 'character', 'N1'), hit('n2', 'character', 'N2'), hit('n3', 'character', 'N3'),+ ]);+ updateProject.mockImplementation(async (_id, patch) => ({ id: 'p1', ...patch }));+ const result = await applyAutoCastToProject('p1', {});+ // only one fresh member fits (49 + 1 = 50)+ expect(result.added).toHaveLength(1);+ expect(updateProject.mock.calls[0][1].cast).toHaveLength(50);+ });+});