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

add Catalog → Story Builder remix bridge: multi-select ingredients seed a new story

[._.]/ Adam Eivy8954012eacd4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0865a2ec6f..7240eddde0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -41,6 +41,7 @@
- **[issue-1633] A new "Start a Story" page gives you one clear front door for beginning a story.** Instead of guessing whether to open the Story Builder, the Importer, or the Writers Room, you now pick how you want to begin — from an idea, from an existing work, or by writing prose — and the page routes you into the right tool. You can also choose up front whether to start a fresh universe or attach the story to one you already have; that choice carries through to the Story Builder and Importer automatically. All the existing pages stay exactly where they were — this just adds a signposted entry point (reachable from the sidebar, ⌘K, and voice). (First phase of the larger creative-onramp effort; prose-mode universe linking comes later.)
- **[issue-1633] Brain notes can now flow into the creative Catalog — making it the one place your ideas, characters, and scenes collect as reusable ingredients.** Two new paths: (1) every Brain record (idea, journal memory, project, admin item, person) gets a **Send to Catalog** button that runs it through the same extract→review→commit pipeline as paste/URL/voice, so a captured thought becomes typed ingredients (characters/scenes/ideas/…) you confirm before keeping. (2) A sticky **Creative** toggle on the Brain capture box (Inbox + Quick Capture) flags a note as a creative idea at capture time — todos and links stay out — and a **Send N creative notes → Catalog** action in the inbox batches the flagged notes into one ingest review when you're ready. Reuses the existing catalog ingest flow end-to-end; no new data model. (`server/services/catalogIngestSources.js`, `server/services/brain.js`, `client/src/components/brain/tabs/InboxTab.jsx`, `client/src/components/QuickBrainCapture.jsx`, `client/src/pages/CatalogIngest.jsx`)
- **[issue-1722] Batch-sent creative notes now drop out of the inbox once their Catalog ingest is committed — so you can't accidentally send the same notes twice.** Previously, after sending your flagged creative notes to the Catalog, the "N creative notes ready" banner kept showing them and a return trip would re-submit the same text. Now the notes are marked consumed the moment you commit ingredients from that review (not on mere navigation — abandoning the review leaves them re-sendable), so the banner clears itself for the notes you've already turned into ingredients.
+- **[issue-1761] Remix Catalog ingredients straight into a new story — the first output-side bridge of the creative pipeline.** The Catalog now has multi-select: tick any characters/places/objects/ideas/scenes, then **Remix into… → Story Builder** carries them across. Story Builder opens seeded — the chosen ingredients show as chips and the seed-idea field is pre-filled from their summaries (yours to edit), and when you create the story each ingredient is linked to the new series via the existing `catalog_ingredient_refs` table, so it shows up in that ingredient's "Appears in" panel. No new data model and no parallel copy of your ingredients — the story and the Catalog share one graph. The handoff is intentionally generic (`remix.ingredientIds`) and the action is a menu with one target today, so adding further remix destinations (Creative Director casting, portrait gen) is additive. Story Builder creation is unchanged when you don't remix. (First remix slice of the #1721 creative-pipeline epic.) (`server/lib/catalogValidation.js`, `server/services/catalogDB.js`, `server/routes/catalog.js`, `server/lib/storyBuilderValidation.js`, `server/services/storyBuilder.js`, `client/src/pages/Catalog.jsx`, `client/src/pages/StoryBuilder.jsx`, `client/src/services/apiCatalog.js`)
## Chief of Staff
diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsx
index 9698acbfc4..7928e92485 100644
--- a/client/src/pages/Catalog.jsx
+++ b/client/src/pages/Catalog.jsx
@@ -9,8 +9,8 @@
*/
import { useState, useEffect, useCallback } from 'react';
-import { Link } from 'react-router-dom';
-import { Sparkles, Plus, Search, FileInput, Trash2, Loader2, RefreshCw } from 'lucide-react';
+import { Link, useNavigate } from 'react-router-dom';
+import { Sparkles, Plus, Search, FileInput, Trash2, Loader2, RefreshCw, Wand2, X } from 'lucide-react';
import toast from '../components/ui/Toast';
import {
listCatalogIngredients,
@@ -61,11 +61,26 @@ function CardThumb({ mediaKey, alt }) {
);
}
+// Remix targets — destinations the user can hand a multi-selected set of
+// ingredients off to. Today there's only Story Builder; the array shape keeps a
+// second target a one-line addition. The handoff state is intentionally generic
+// (`remix.ingredientIds`), NOT story-builder-specific, so a new destination just
+// 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' },
+];
+
export default function Catalog() {
+ const navigate = useNavigate();
// Merged type registry (system + user-defined). `types` drives the filter
// chips + the New-form dropdown; `getType` resolves badge/primary-content.
const { types: TYPES, getType } = useCatalogTypes();
const [items, setItems] = useState([]);
+ // Multi-select for "Remix into…". A Set of selected ingredient ids; selection
+ // is a distinct gesture from opening a card (which navigates to the detail
+ // page), so the per-card checkbox stops propagation.
+ const [selectedIds, setSelectedIds] = useState(() => new Set());
+ const [remixMenuOpen, setRemixMenuOpen] = useState(false);
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(true);
const [selectedType, setSelectedType] = useState('');
@@ -165,6 +180,14 @@ export default function Catalog() {
const confirmDelete = async (it) => {
setArmedId(null);
+ // A deleted ingredient can't be remixed — drop it from the selection so the
+ // action bar count stays honest.
+ setSelectedIds((prev) => {
+ if (!prev.has(it.id)) return prev;
+ const next = new Set(prev);
+ next.delete(it.id);
+ return next;
+ });
// Capture the original index so a failed delete restores in place rather
// than jumping the row to the top of the list.
const originalIdx = items.findIndex((x) => x.id === it.id);
@@ -225,6 +248,30 @@ export default function Catalog() {
setShowForm(false);
};
+ // ── Multi-select "Remix into…" ────────────────────────────────────────────
+ const toggleSelect = (id) => {
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ };
+
+ const clearSelection = () => {
+ setSelectedIds(new Set());
+ setRemixMenuOpen(false);
+ };
+
+ // Hand the selected ids off to the chosen target with a GENERIC state key
+ // (`remix.ingredientIds`) so any future destination reads the same shape.
+ const handleRemix = (target) => {
+ const ingredientIds = [...selectedIds];
+ if (ingredientIds.length === 0) return;
+ setRemixMenuOpen(false);
+ navigate(target.to, { state: { remix: { ingredientIds } } });
+ };
+
return (
<div>
<div className="flex items-center justify-between mb-6 flex-wrap gap-3">
@@ -389,16 +436,35 @@ export default function Catalog() {
<ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
{items.map((it) => {
const armed = armedId === it.id;
+ const selected = selectedIds.has(it.id);
const name = it.name || '(untitled)';
// The card is one big Link so clicking anywhere (name, badge, tags,
- // snippet, empty body) opens the editor. The delete control sits in
- // absolute-positioned overlay so it intercepts clicks before they
- // bubble to the link.
+ // snippet, empty body) opens the editor. The delete control + the
+ // selection checkbox sit in absolute-positioned overlays (siblings
+ // of the Link, not descendants) so their clicks never bubble to the
+ // anchor; the checkbox also stops propagation defensively.
return (
- <li key={it.id} className="relative bg-port-card border border-port-border rounded-lg hover:border-port-accent/60 transition-colors">
+ <li
+ key={it.id}
+ className={`relative bg-port-card border rounded-lg transition-colors ${
+ selected
+ ? 'border-port-accent ring-1 ring-port-accent'
+ : 'border-port-border hover:border-port-accent/60'
+ }`}
+ >
+ <span className="absolute top-2 left-2 z-10 flex items-center justify-center rounded bg-port-card/90 border border-port-border">
+ <input
+ type="checkbox"
+ checked={selected}
+ onChange={() => toggleSelect(it.id)}
+ onClick={(e) => e.stopPropagation()}
+ aria-label={`Select ${name}`}
+ className="w-4 h-4 m-1 accent-port-accent cursor-pointer"
+ />
+ </span>
<Link
to={`/catalog/${encodeURIComponent(it.type)}/${encodeURIComponent(it.id)}`}
- className={`flex gap-3 p-3 min-h-[88px] ${armed ? 'pr-32' : 'pr-10'}`}
+ className={`flex gap-3 p-3 pl-10 min-h-[88px] ${armed ? 'pr-32' : 'pr-10'}`}
>
<CardThumb mediaKey={it.thumbnailKey} alt={name} />
<span className="flex flex-col gap-2 min-w-0 flex-1">
@@ -455,6 +521,55 @@ export default function Catalog() {
})}
</ul>
)}
+
+ {selectedIds.size > 0 && (
+ <div className="sticky bottom-0 left-0 right-0 mt-4 -mx-4 md:-mx-6 px-4 md:px-6 py-3 bg-port-card/95 backdrop-blur border-t border-port-border flex items-center justify-between gap-3 flex-wrap z-20">
+ <span className="text-sm text-white font-medium">
+ {selectedIds.size} selected
+ </span>
+ <div className="flex items-center gap-2">
+ <div className="relative">
+ <button
+ type="button"
+ onClick={() => setRemixMenuOpen((o) => !o)}
+ aria-haspopup="menu"
+ aria-expanded={remixMenuOpen}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"
+ >
+ <Wand2 size={16} aria-hidden="true" />
+ Remix into…
+ </button>
+ {remixMenuOpen && (
+ <ul
+ role="menu"
+ className="absolute right-0 bottom-full mb-2 min-w-[180px] bg-port-card border border-port-border rounded-lg shadow-lg overflow-hidden"
+ >
+ {REMIX_TARGETS.map((t) => (
+ <li key={t.id} role="none">
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => handleRemix(t)}
+ className="w-full text-left px-3 py-2 text-sm text-gray-200 hover:bg-port-bg hover:text-white"
+ >
+ {t.label}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={clearSelection}
+ className="inline-flex items-center gap-1 px-3 py-2 rounded-lg border border-port-border text-gray-300 hover:text-white text-sm"
+ >
+ <X size={16} aria-hidden="true" />
+ Clear
+ </button>
+ </div>
+ </div>
+ )}
</div>
);
}
diff --git a/client/src/pages/Catalog.test.jsx b/client/src/pages/Catalog.test.jsx
index cc0b0b65bd..e58872322e 100644
--- a/client/src/pages/Catalog.test.jsx
+++ b/client/src/pages/Catalog.test.jsx
@@ -2,6 +2,15 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
+// Spy on navigation so the "Remix into…" handoff can assert the target route +
+// the generic `remix.ingredientIds` state payload. MemoryRouter still supplies
+// the real Link/router context.
+const navigateMock = vi.hoisted(() => vi.fn());
+vi.mock('react-router-dom', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, useNavigate: () => navigateMock };
+});
+
vi.mock('../services/apiCatalog', () => ({
listCatalogIngredients: vi.fn(),
createCatalogIngredient: vi.fn(),
@@ -221,6 +230,51 @@ describe('Catalog page', () => {
expect(img.getAttribute('src')).toBe('/data/images/hero.png');
});
+ it('multi-selects ingredients and remixes them into Story Builder with a generic state payload', async () => {
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+
+ // No action bar until something is selected.
+ expect(screen.queryByText(/selected$/i)).toBeNull();
+
+ fireEvent.click(screen.getByLabelText('Select Echo Saint'));
+ fireEvent.click(screen.getByLabelText('Select Old Harbor'));
+ await waitFor(() => expect(screen.getByText('2 selected')).toBeTruthy());
+
+ // Open the Remix menu and choose Story Builder.
+ fireEvent.click(screen.getByRole('button', { name: /Remix into/i }));
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Story Builder' }));
+
+ expect(navigateMock).toHaveBeenCalledWith('/story-builder', {
+ state: { remix: { ingredientIds: ['i-1', 'i-2'] } },
+ });
+ });
+
+ it('toggling a selection checkbox does not navigate to the card detail', async () => {
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+ fireEvent.click(screen.getByLabelText('Select Echo Saint'));
+ // Selection is a distinct gesture from opening the card — no navigation.
+ expect(navigateMock).not.toHaveBeenCalled();
+ expect(screen.getByText('1 selected')).toBeTruthy();
+ });
+
+ it('drops a deleted ingredient from the selection so the count stays honest', async () => {
+ deleteCatalogIngredient.mockResolvedValue({ success: true });
+ renderCatalog();
+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
+
+ fireEvent.click(screen.getByLabelText('Select Echo Saint'));
+ fireEvent.click(screen.getByLabelText('Select Old Harbor'));
+ expect(screen.getByText('2 selected')).toBeTruthy();
+
+ fireEvent.click(screen.getByLabelText(/Delete Echo Saint/i));
+ const yesBtn = await screen.findByRole('button', { name: /^Yes$/i });
+ await act(async () => { fireEvent.click(yesBtn); });
+
+ await waitFor(() => expect(screen.getByText('1 selected')).toBeTruthy());
+ });
+
it('renders a user-defined type as a filter chip from the merged registry', async () => {
listCatalogTypes.mockResolvedValue({
types: [{ id: 'faction', label: 'Faction', system: false, badgeColor: 'bg-gray-500/20 text-gray-300 border-gray-500/40', primaryContentKey: 'creed', primaryContentLabel: 'Creed', snippetFallbackKeys: ['creed'], fields: [] }],
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index a34723f637..4403395228 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
-import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom';
+import { useParams, useNavigate, useSearchParams, useLocation, Link } from 'react-router-dom';
import { filterSelectableModels } from '../utils/providers';
import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';
import { descriptorForCanonEntry } from '../lib/canonPrompt';
@@ -26,11 +26,12 @@ import {
setStorySessionSync, reconcileStorySession, storyStepProgressSseUrl,
getUniverse, getPipelineSeries, listPipelineIssues,
analyzeImport, commitImport, retryImporterIssues, IMPORTER_CONTENT_TYPES,
- getProviders,
+ getProviders, listCatalogIngredientsByIds,
} from '../services/api';
import ArcCanvas from '../components/pipeline/ArcCanvas';
import { useArcCanvasSync } from '../hooks/useArcCanvasSync';
import { BEAT_KIND_COLORS, getBeatKindColor } from '../lib/beatColors';
+import { getCatalogType } from '../lib/catalogTypes';
// Mirror Importer.jsx's commit picker — only these arc fields are sent on commit.
const ARC_FIELDS_TO_COMMIT = ['logline', 'summary', 'protagonistArc', 'themes', 'shape'];
@@ -51,6 +52,52 @@ const CONTENT_TYPE_LABELS = {
'short-story': 'Short story', novel: 'Novel', screenplay: 'Screenplay', 'comic-script': 'Comic script',
};
+// Compose a starter-idea prefill from a set of catalog ingredients (the Catalog
+// "Remix into… → Story Builder" handoff). Ingredients are grouped by type, with
+// a header line per group (e.g. `Characters:`) and one bullet per ingredient
+// (`- {name}: {summary}`) where the summary is the first ~120 chars of the
+// payload's description/summary/text. The whole composed text is capped at 4000
+// chars to match the seedIdea field. Pure — unit-tested in StoryBuilder.test.jsx.
+const SEED_SUMMARY_KEYS = ['description', 'summary', 'text'];
+const SEED_MAX_CHARS = 4000;
+const SEED_SUMMARY_CHARS = 120;
+
+// "character" → "Characters:" — prefer the catalog registry's canonical label
+// (so idea/scene/concept get proper plurals), naive-pluralizing a user-defined
+// type's id as a fallback. Mirrors `seedGroupHeading` in server storyBuilder.js
+// so the prefill the user sees matches the server's fallback composition.
+function seedGroupHeading(type) {
+ const label = getCatalogType(type)?.label;
+ const base = label || (type ? `${type.charAt(0).toUpperCase()}${type.slice(1)}` : 'Other');
+ return base.endsWith('s') ? base : `${base}s`;
+}
+
+export function composeSeedFromIngredients(ingredients) {
+ const list = Array.isArray(ingredients) ? ingredients : [];
+ if (list.length === 0) return '';
+ // Preserve first-seen group order so the prefill reads in selection order.
+ const groups = new Map();
+ for (const ing of list) {
+ if (!ing) continue;
+ const type = (ing.type || 'other').trim() || 'other';
+ if (!groups.has(type)) groups.set(type, []);
+ groups.get(type).push(ing);
+ }
+ const lines = [];
+ for (const [type, members] of groups) {
+ lines.push(`${seedGroupHeading(type)}:`);
+ for (const ing of members) {
+ const name = (ing.name || '').trim() || '(untitled)';
+ const payload = ing.payload || {};
+ const rawKey = SEED_SUMMARY_KEYS.find((k) => typeof payload[k] === 'string' && payload[k].trim());
+ const summary = rawKey ? payload[rawKey].trim().slice(0, SEED_SUMMARY_CHARS) : '';
+ lines.push(summary ? `- ${name}: ${summary}` : `- ${name}`);
+ }
+ lines.push('');
+ }
+ return lines.join('\n').trim().slice(0, SEED_MAX_CHARS);
+}
+
// Shared AI provider + model picker. The selection applies to EVERY Story
// Builder operation (idea expand, aesthetic, arc, reader map, character refine,
// and the importer's analyze) — see the session.llm fallback in the conductor.
@@ -95,6 +142,7 @@ function ProviderModelPicker({ value, onChange }) {
function StoryBuilderIndex() {
const navigate = useNavigate();
+ const location = useLocation();
const [searchParams] = useSearchParams();
// The "Start a Story" onramp can deep-link here with a pre-chosen universe
// (?universeId=…); pass it through so the new session attaches to it instead
@@ -105,16 +153,48 @@ function StoryBuilderIndex() {
const [title, setTitle] = useState('');
const [seedIdea, setSeedIdea] = useState('');
const [creating, setCreating] = useState(false);
+ // Catalog "Remix into… → Story Builder" handoff. The ingredient ids arrive in
+ // the generic `location.state.remix.ingredientIds`; we hydrate them via the
+ // batch endpoint for the chip list + the seed prefill, and forward the ids on
+ // create so the server can attach them to the new session.
+ const [remixIds, setRemixIds] = useState([]);
+ const [remixIngredients, setRemixIngredients] = useState([]);
useEffect(() => {
listStorySessions({ silent: true }).then(setSessions).catch(() => setSessions([]));
}, []);
+ // Consume the remix handoff once at mount, then clear the history state so a
+ // refresh doesn't re-seed (mirrors CatalogIngest's prefill-consume pattern).
+ 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);
+ listCatalogIngredientsByIds(cleanIds, { silent: true })
+ .then((res) => {
+ const list = Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);
+ setRemixIngredients(list);
+ // Prefill only if the user hasn't already typed a seed — don't clobber.
+ setSeedIdea((prev) => (prev.trim() ? prev : composeSeedFromIngredients(list)));
+ })
+ .catch(() => {});
+ // Clear the handoff state so a refresh doesn't re-seed (ids already captured).
+ navigate('.', { replace: true, state: {} });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
const create = async () => {
if (!title.trim()) { toast.error('Give your story a working title'); return; }
setCreating(true);
const created = await createStorySession(
- { title: title.trim(), seedIdea: seedIdea.trim(), universeId: onrampUniverseId },
+ {
+ title: title.trim(),
+ seedIdea: seedIdea.trim(),
+ universeId: onrampUniverseId,
+ ...(remixIds.length ? { catalogIngredientIds: remixIds } : {}),
+ },
{ silent: true },
)
.catch((err) => { toast.error(err?.message || 'Failed to create'); return null; });
@@ -148,6 +228,24 @@ function StoryBuilderIndex() {
{mode === 'seed' ? (
<div className="p-4 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">
+ Seeding from {remixIngredients.length} 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>
+ </div>
+ )}
<div>
<label htmlFor="stb-title" className="block text-sm text-gray-400 mb-1">Universe / story name</label>
<input
diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsx
index eac4b4c517..3e9e4be89d 100644
--- a/client/src/pages/StoryBuilder.test.jsx
+++ b/client/src/pages/StoryBuilder.test.jsx
@@ -43,6 +43,7 @@ const api = vi.hoisted(() => ({
generateImage: vi.fn(),
updateUniverse: vi.fn(),
updatePipelineSeries: vi.fn(),
+ listCatalogIngredientsByIds: vi.fn(),
}));
vi.mock('../services/api', () => api);
@@ -64,10 +65,10 @@ vi.mock('../components/pipeline/ArcCanvas', () => ({
default: ({ series }) => <div data-testid="arc-canvas">ArcCanvas[{series?.id}]</div>,
}));
-import StoryBuilder from './StoryBuilder';
+import StoryBuilder, { composeSeedFromIngredients } from './StoryBuilder';
-const renderAt = (path) => render(
- <MemoryRouter initialEntries={[path]}>
+const renderAt = (entry) => render(
+ <MemoryRouter initialEntries={[entry]}>
<Routes>
<Route path="/story-builder" element={<StoryBuilder />} />
<Route path="/story-builder/:storyId/:step" element={<StoryBuilder />} />
@@ -102,6 +103,43 @@ beforeEach(() => {
api.getUniverse.mockResolvedValue({ id: 'u1', logline: 'L', premise: 'P', styleNotes: 'S', influences: { embrace: [], avoid: [] }, characters: [] });
api.getPipelineSeries.mockResolvedValue({ id: 's1', arc: { logline: 'AL', summary: 'AS', readerMap: { hooks: [{ id: 'rm-1', label: 'Why?' }] } } });
api.listPipelineIssues.mockResolvedValue([]);
+ api.listCatalogIngredientsByIds.mockResolvedValue([]);
+});
+
+describe('composeSeedFromIngredients', () => {
+ it('returns an empty string for no ingredients', () => {
+ expect(composeSeedFromIngredients([])).toBe('');
+ expect(composeSeedFromIngredients(null)).toBe('');
+ });
+
+ it('groups by type with a header line and a bullet (name: summary) per ingredient', () => {
+ const out = composeSeedFromIngredients([
+ { id: 'c1', name: 'Echo Saint', type: 'character', payload: { description: 'A wiry figure in a long coat.' } },
+ { id: 'c2', name: 'Mara', type: 'character', payload: { summary: 'Loyal to a fault.' } },
+ { id: 'p1', name: 'Old Harbor', type: 'place', payload: { text: 'Brine and rust.' } },
+ ]);
+ expect(out).toContain('Characters:');
+ expect(out).toContain('- Echo Saint: A wiry figure in a long coat.');
+ expect(out).toContain('- Mara: Loyal to a fault.');
+ expect(out).toContain('Places:');
+ expect(out).toContain('- Old Harbor: Brine and rust.');
+ });
+
+ it('truncates each summary to ~120 chars and the whole text to 4000', () => {
+ const long = 'x'.repeat(500);
+ const out = composeSeedFromIngredients([{ id: 'c1', name: 'Big', type: 'idea', payload: { description: long } }]);
+ // 120-char summary cap.
+ expect(out).toContain(`- Big: ${'x'.repeat(120)}`);
+ expect(out).not.toContain('x'.repeat(121));
+ expect(out.length).toBeLessThanOrEqual(4000);
+ });
+
+ it('falls back to just the name when no summary field is present', () => {
+ const out = composeSeedFromIngredients([{ id: 'o1', name: 'Relic', type: 'object', payload: {} }]);
+ expect(out).toContain('Objects:');
+ expect(out).toContain('- Relic');
+ expect(out).not.toContain('- Relic:');
+ });
});
describe('StoryBuilder — index', () => {
@@ -112,6 +150,33 @@ describe('StoryBuilder — index', () => {
expect(screen.getByText('Import a finished work')).toBeTruthy();
});
+ it('remix handoff: hydrates selected ingredients into chips + a prefilled seed, and forwards the ids on create', async () => {
+ const { fireEvent } = await import('@testing-library/react');
+ api.listCatalogIngredientsByIds.mockResolvedValue([
+ { id: 'i-1', name: 'Echo Saint', type: 'character', payload: { description: 'A wiry figure in a long coat.' } },
+ { id: 'i-2', name: 'Old Harbor', type: 'place', payload: { summary: 'Brine and rust.' } },
+ ]);
+ api.createStorySession.mockResolvedValue({ id: 'stb-remix', currentStep: 'idea' });
+
+ renderAt({ pathname: '/story-builder', state: { remix: { ingredientIds: ['i-1', 'i-2'] } } });
+
+ // The batch endpoint is hit with the handed-off ids.
+ await waitFor(() => expect(api.listCatalogIngredientsByIds).toHaveBeenCalledWith(['i-1', 'i-2'], expect.objectContaining({ silent: true })));
+ // Chip list + count.
+ expect(await screen.findByText('Seeding from 2 ingredients')).toBeTruthy();
+ // The seed textarea is prefilled from the composed summary.
+ const seed = screen.getByLabelText('Starter idea');
+ await waitFor(() => expect(seed.value).toContain('Echo Saint'));
+ expect(seed.value).toContain('Characters:');
+
+ fireEvent.change(screen.getByLabelText('Universe / story name'), { target: { value: 'Salt Run' } });
+ fireEvent.click(screen.getByRole('button', { name: /Create & begin/i }));
+ await waitFor(() => expect(api.createStorySession).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'Salt Run', catalogIngredientIds: ['i-1', 'i-2'] }),
+ expect.objectContaining({ silent: true }),
+ ));
+ });
+
it('import tab: analyze → preview → import & build creates an import-mode session', async () => {
const { fireEvent } = await import('@testing-library/react');
api.analyzeImport.mockResolvedValue({
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index 7e5616c669..4acadd5651 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -67,6 +67,19 @@ export const listCatalogIngredients = ({ type, tag, q, limit, offset, ...options
return request(`/catalog/ingredients${params.toString() ? `?${params}` : ''}`, options);
};
+// Batch fetch ingredients by id (max 50 server-side) — used by the Story
+// Builder remix handoff to hydrate the catalog ingredients the user selected.
+// The `ids` filter rides the normal paged list endpoint, which returns the
+// `{ items, nextOffset }` envelope; this unwraps to a plain array of ingredient
+// objects for callers. Empty/falsy ids are dropped before the request.
+export const listCatalogIngredientsByIds = async (ids = [], options) => {
+ const list = (Array.isArray(ids) ? ids : []).filter(Boolean);
+ const params = new URLSearchParams();
+ params.set('ids', list.join(','));
+ const res = await request(`/catalog/ingredients?${params}`, options);
+ return Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);
+};
+
export const getCatalogIngredient = (id, options) =>
request(`/catalog/ingredients/${enc(id)}`, options);
diff --git a/client/src/services/apiStoryBuilder.js b/client/src/services/apiStoryBuilder.js
index c2f6a5d708..95f520964e 100644
--- a/client/src/services/apiStoryBuilder.js
+++ b/client/src/services/apiStoryBuilder.js
@@ -10,6 +10,9 @@ export const listStorySessions = (options = {}) => request('/story-builder', opt
export const getStorySession = (id, options = {}) => request(`/story-builder/${id}`, options);
+// payload accepts { title, intakeMode, seedIdea, universeId, seriesId, llm, ... }
+// plus an optional `catalogIngredientIds: string[]` (max 50) — the Catalog
+// "Remix into… → Story Builder" handoff seeds the new session from these.
export const createStorySession = (payload, options = {}) => request('/story-builder', {
method: 'POST',
body: JSON.stringify(payload),
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 88f66b0459..65c4f42098 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -276,6 +276,16 @@ export const catalogRevisionRestoreSchema = z.object({
}).strict();
export const catalogIngredientQuerySchema = z.object({
+ // Batch-fetch by id. The wire form is a CSV string (`?ids=a,b,c`); we
+ // preprocess it into a trimmed, empties-dropped, ≤50 string[]. An empty/
+ // all-blank CSV collapses to `undefined` so the field reads cleanly as
+ // absent (the route/service then falls through to the type/tag/q filters).
+ // When present, `ids` takes precedence over type/tag/q in `listIngredients`.
+ ids: z.preprocess((v) => {
+ if (typeof v !== 'string') return v;
+ const parts = v.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 50);
+ return parts.length ? parts : undefined;
+ }, z.array(z.string().trim().min(1).max(64)).max(50).optional()),
type: ingredientTypeGate.optional(),
tag: tag.optional(),
q: z.string().trim().max(500).optional(),
diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.js
index 217986cced..e78b0fa8a4 100644
--- a/server/lib/catalogValidation.test.js
+++ b/server/lib/catalogValidation.test.js
@@ -216,6 +216,31 @@ describe('catalogValidation — catalogIngredientQuerySchema', () => {
it('rejects negative offset', () => {
expect(() => catalogIngredientQuerySchema.parse({ offset: '-1' })).toThrow();
});
+
+ it('preprocesses a CSV ids string into a trimmed string[]', () => {
+ const out = catalogIngredientQuerySchema.parse({ ids: 'a, b ,c' });
+ expect(out.ids).toEqual(['a', 'b', 'c']);
+ });
+
+ it('drops empty segments and collapses an all-blank ids string to undefined', () => {
+ expect(catalogIngredientQuerySchema.parse({ ids: 'a,,,b' }).ids).toEqual(['a', 'b']);
+ expect(catalogIngredientQuerySchema.parse({ ids: ' , , ' }).ids).toBeUndefined();
+ expect(catalogIngredientQuerySchema.parse({ ids: '' }).ids).toBeUndefined();
+ });
+
+ it('omits ids cleanly when absent', () => {
+ expect(catalogIngredientQuerySchema.parse({ limit: '10' }).ids).toBeUndefined();
+ });
+
+ it('caps ids at 50 entries (extra trimmed before length validation)', () => {
+ const csv = Array.from({ length: 80 }, (_, i) => `id${i}`).join(',');
+ const out = catalogIngredientQuerySchema.parse({ ids: csv });
+ expect(out.ids).toHaveLength(50);
+ });
+
+ it('rejects an oversized single id token (>64 chars)', () => {
+ expect(() => catalogIngredientQuerySchema.parse({ ids: 'x'.repeat(65) })).toThrow();
+ });
});
describe('catalogValidation — catalogIngredientLinkSchema', () => {
diff --git a/server/lib/storyBuilderValidation.js b/server/lib/storyBuilderValidation.js
index 72e57d2810..b5c9e7bbd0 100644
--- a/server/lib/storyBuilderValidation.js
+++ b/server/lib/storyBuilderValidation.js
@@ -20,6 +20,12 @@ export const storySessionCreateSchema = z.object({
// Import mode supplies pre-created ids; seed mode mints shells server-side.
universeId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
seriesId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
+ // Optional Catalog ingredients to seed + link to the new series (#1761).
+ // Seed mode links each surviving ingredient to the minted series via
+ // catalog_ingredient_refs (ref_kind='series'); honors the convergence
+ // contract (no parallel data model). Additive + optional ⇒ older clients
+ // that omit it are unaffected.
+ catalogIngredientIds: z.array(z.string().trim().max(64)).max(50).optional(),
// Picker choice that drives every Story Builder operation; nullable so the
// UI can send "use the stage default" explicitly.
llm: z.object({
diff --git a/server/lib/storyBuilderValidation.test.js b/server/lib/storyBuilderValidation.test.js
new file mode 100644
index 0000000000..81a29ae34d
--- /dev/null
+++ b/server/lib/storyBuilderValidation.test.js
@@ -0,0 +1,58 @@
+/**
+ * Zod boundary tests for the Story Builder validators.
+ *
+ * Focused on the #1761 additive `catalogIngredientIds` field on
+ * storySessionCreateSchema — the schema is `.strict()`, so the field MUST be
+ * declared for the create route to accept it. These also pin the
+ * back-compat guarantee: a create body that omits it still parses.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { storySessionCreateSchema } from './storyBuilderValidation.js';
+
+describe('storyBuilderValidation — storySessionCreateSchema.catalogIngredientIds', () => {
+ it('accepts a create body carrying catalogIngredientIds', () => {
+ const out = storySessionCreateSchema.parse({
+ title: 'Salt Run',
+ catalogIngredientIds: ['cat-character-1', 'cat-place-2'],
+ });
+ expect(out.catalogIngredientIds).toEqual(['cat-character-1', 'cat-place-2']);
+ });
+
+ it('omits the field cleanly when absent (back-compat)', () => {
+ const out = storySessionCreateSchema.parse({ title: 'No Ingredients' });
+ expect(out.catalogIngredientIds).toBeUndefined();
+ });
+
+ it('accepts an empty array', () => {
+ const out = storySessionCreateSchema.parse({ title: 'X', catalogIngredientIds: [] });
+ expect(out.catalogIngredientIds).toEqual([]);
+ });
+
+ it('trims each id', () => {
+ const out = storySessionCreateSchema.parse({
+ title: 'X',
+ catalogIngredientIds: [' cat-1 '],
+ });
+ expect(out.catalogIngredientIds).toEqual(['cat-1']);
+ });
+
+ it('rejects an oversized array (>50)', () => {
+ const ids = Array.from({ length: 51 }, (_, i) => `cat-${i}`);
+ expect(() => storySessionCreateSchema.parse({ title: 'X', catalogIngredientIds: ids })).toThrow();
+ });
+
+ it('rejects an id longer than 64 chars', () => {
+ expect(() => storySessionCreateSchema.parse({
+ title: 'X',
+ catalogIngredientIds: ['x'.repeat(65)],
+ })).toThrow();
+ });
+
+ it('rejects a non-array catalogIngredientIds', () => {
+ expect(() => storySessionCreateSchema.parse({
+ title: 'X',
+ catalogIngredientIds: 'cat-1',
+ })).toThrow();
+ });
+});
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 43fab7962f..fc343e0941 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -196,6 +196,7 @@ router.get('/tags', asyncHandler(async (req, res) => {
router.get('/ingredients', asyncHandler(async (req, res) => {
const params = validateRequest(catalogIngredientQuerySchema, req.query);
res.json(await catalogDB.listIngredients({
+ ids: params.ids,
type: params.type,
tag: params.tag,
query: params.q,
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 14bfd22d29..0dec4e8609 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -700,23 +700,32 @@ const THUMBNAIL_KEY_SUBQUERY = `(
LIMIT 1
) AS thumbnail_key`;
-export async function listIngredients({ type, tag, query: q, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {
+export async function listIngredients({ ids, type, tag, query: q, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {
const conditions = ['deleted = false'];
const params = [];
let idx = 1;
- if (type) {
- conditions.push(`type = $${idx++}`);
- params.push(type);
- }
- if (tag) {
- conditions.push(`$${idx++} = ANY(tags)`);
- params.push(tag);
- }
+ // Batch-fetch by id (Story Builder catalog→series linking, #1761). When
+ // present, `ids` takes precedence over type/tag/q — they're skipped so the
+ // caller gets exactly the requested (still non-deleted) rows.
+ const byIds = Array.isArray(ids) && ids.length > 0;
let qIdx = null;
- if (q) {
- qIdx = idx++;
- conditions.push(`search_tsv @@ websearch_to_tsquery('english', $${qIdx})`);
- params.push(q);
+ if (byIds) {
+ conditions.push(`id = ANY($${idx++})`);
+ params.push(ids);
+ } else {
+ if (type) {
+ conditions.push(`type = $${idx++}`);
+ params.push(type);
+ }
+ if (tag) {
+ conditions.push(`$${idx++} = ANY(tags)`);
+ params.push(tag);
+ }
+ if (q) {
+ qIdx = idx++;
+ conditions.push(`search_tsv @@ websearch_to_tsquery('english', $${qIdx})`);
+ params.push(q);
+ }
}
if (embeddingMissing) {
conditions.push('embedding IS NULL');
@@ -899,6 +908,28 @@ export async function linkIngredientToRef(ingredientId, refKind, refId, role) {
);
}
+// Catalog ingredient `type` → series ref role (#1761). Anything outside this
+// map (idea/scene/user-defined types) links as a generic 'mentioned' ref.
+// Lives here, next to the link primitive, so every remix target that attaches
+// ingredients to a series shares one role vocabulary instead of inlining its own.
+const SERIES_REF_ROLE_BY_TYPE = Object.freeze({
+ character: 'cast',
+ place: 'canon-place',
+ object: 'canon-object',
+});
+export const seriesRefRoleForType = (type) => SERIES_REF_ROLE_BY_TYPE[type] || 'mentioned';
+
+// Link a batch of already-resolved catalog ingredients to a series via
+// catalog_ingredient_refs (#1761) — the convergence contract's single data
+// model. The inserts are mutually independent, so they fan out. Returns the
+// ingredients actually linked (those with an id).
+export async function linkIngredientsToSeries(seriesId, 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, 'series', seriesId, seriesRefRoleForType(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
diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.js
index 70eb7614ea..2920492f8f 100644
--- a/server/services/catalogDB.test.js
+++ b/server/services/catalogDB.test.js
@@ -61,6 +61,21 @@ afterAll(async () => {
await close();
});
+// Pure helper — the type→series-role vocabulary (#1761). No DB, so it runs in
+// the normal (non-test:db) suite and stays the single source of truth for the
+// roles every remix target uses when attaching ingredients to a series.
+describe('seriesRefRoleForType', () => {
+ it('maps known types to canon roles and everything else to mentioned', () => {
+ expect(catalogDB.seriesRefRoleForType('character')).toBe('cast');
+ expect(catalogDB.seriesRefRoleForType('place')).toBe('canon-place');
+ expect(catalogDB.seriesRefRoleForType('object')).toBe('canon-object');
+ expect(catalogDB.seriesRefRoleForType('scene')).toBe('mentioned');
+ expect(catalogDB.seriesRefRoleForType('idea')).toBe('mentioned');
+ expect(catalogDB.seriesRefRoleForType('faction')).toBe('mentioned'); // user-defined
+ expect(catalogDB.seriesRefRoleForType(undefined)).toBe('mentioned');
+ });
+});
+
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;
@@ -185,6 +200,32 @@ describe.skipIf(!dbReady)('catalogDB (Postgres CRUD round-trip)', () => {
expect(full.embedding).toHaveLength(768);
});
+ it('lists by ids (batch fetch), excludes soft-deleted, and ignores type/tag (#1761)', async () => {
+ if (!requireDb('list by ids')) return;
+ const a = await catalogDB.createIngredient({ type: 'character', name: 'Batch Alpha', tags: ['hero'] });
+ const b = await catalogDB.createIngredient({ type: 'place', name: 'Batch Beta' });
+ const gone = await catalogDB.createIngredient({ type: 'object', name: 'Batch Gone' });
+ createdIngredientIds.add(a.id);
+ createdIngredientIds.add(b.id);
+ createdIngredientIds.add(gone.id);
+ await catalogDB.deleteIngredient(gone.id);
+
+ // ids returns exactly the requested non-deleted rows...
+ const { items } = await catalogDB.listIngredients({ ids: [a.id, b.id, gone.id, 'cat-missing'], limit: 200 });
+ const got = new Set(items.map((i) => i.id));
+ expect(got.has(a.id)).toBe(true);
+ expect(got.has(b.id)).toBe(true);
+ // ...and never the soft-deleted or unknown ids.
+ expect(got.has(gone.id)).toBe(false);
+ expect(got.has('cat-missing')).toBe(false);
+
+ // ids takes precedence over type/tag — a mismatched type filter is ignored.
+ const { items: precedence } = await catalogDB.listIngredients({
+ ids: [a.id, b.id], type: 'object', tag: 'nonexistent', limit: 200,
+ });
+ expect(new Set(precedence.map((i) => i.id))).toEqual(new Set([a.id, b.id]));
+ });
+
it('links an ingredient to a ref, lists both directions, then soft-unlinks', async () => {
if (!requireDb('ref link/unlink')) return;
const ing = await catalogDB.createIngredient({ type: 'character', name: 'Linker McRef' });
@@ -208,6 +249,27 @@ describe.skipIf(!dbReady)('catalogDB (Postgres CRUD round-trip)', () => {
expect(await catalogDB.listIngredientsForRef('series', refId)).toHaveLength(0);
});
+ it('linkIngredientsToSeries batch-links a mixed set with type-mapped roles (#1761)', async () => {
+ if (!requireDb('batch link to series')) return;
+ const chr = await catalogDB.createIngredient({ type: 'character', name: 'Batch Mira' });
+ const plc = await catalogDB.createIngredient({ type: 'place', name: 'Batch Foundry' });
+ const scn = await catalogDB.createIngredient({ type: 'scene', name: 'Batch Opening' });
+ [chr, plc, scn].forEach((i) => createdIngredientIds.add(i.id));
+ const seriesId = `series-batch-${chr.id}`;
+
+ const linked = await catalogDB.linkIngredientsToSeries(seriesId, [chr, plc, scn]);
+ expect(linked).toHaveLength(3);
+
+ const forRef = await catalogDB.listIngredientsForRef('series', seriesId);
+ const roleById = Object.fromEntries(forRef.map((r) => [r.ingredient.id, r.role]));
+ expect(roleById[chr.id]).toBe('cast');
+ expect(roleById[plc.id]).toBe('canon-place');
+ expect(roleById[scn.id]).toBe('mentioned');
+
+ // Empty / id-less input is a no-op.
+ expect(await catalogDB.linkIngredientsToSeries(seriesId, [])).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/storyBuilder.js b/server/services/storyBuilder.js
index 8b1054bbab..44d7289f67 100644
--- a/server/services/storyBuilder.js
+++ b/server/services/storyBuilder.js
@@ -46,6 +46,8 @@ 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 { getCatalogType } from '../lib/catalogTypes.js';
import { createUniverse, deleteUniverse, getUniverse, updateUniverse } from './universeBuilder.js';
import { expandWorldTemplate } from './universeBuilderExpand.js';
import { refineWorldPrompts } from './universeBuilderRefine.js';
@@ -75,6 +77,60 @@ export const TITLE_MAX = 200;
export const SEED_MAX = 4000;
export const INTAKE_MODES = Object.freeze(['seed', 'import']);
+// Group → header label for the composed fallback seed. Prefer the catalog
+// registry's canonical label (so idea/scene/concept get proper plurals and
+// match the client's prefill), naive-pluralizing a user-defined type's id as a
+// fallback. Mirrors `seedGroupHeading` in client StoryBuilder.jsx.
+function seedGroupHeading(type) {
+ const label = getCatalogType(type)?.label;
+ const base = label || (isStr(type) && type ? `${type.charAt(0).toUpperCase()}${type.slice(1)}` : 'Other');
+ return base.endsWith('s') ? base : `${base}s`;
+}
+
+// Compose a fallback seed string from resolved catalog ingredients (#1761),
+// used when the user supplies ingredients but no seedIdea so the minted
+// universe/series shells aren't empty. Groups by type with a header line per
+// group and one `- {name}: {summary}` bullet per ingredient (summary = first
+// ~120 chars of the payload's description/summary/text; omitted, with the
+// `: `, when empty). Capped at SEED_MAX with a trailing ellipsis on overflow.
+function composeSeedFromIngredients(ingredients) {
+ const byType = new Map();
+ for (const ing of ingredients) {
+ const list = byType.get(ing.type) || [];
+ list.push(ing);
+ byType.set(ing.type, list);
+ }
+ const lines = [];
+ for (const [type, list] of byType) {
+ lines.push(`${seedGroupHeading(type)}:`);
+ for (const ing of list) {
+ const p = ing.payload && typeof ing.payload === 'object' ? ing.payload : {};
+ const raw = isStr(p.description) ? p.description
+ : isStr(p.summary) ? p.summary
+ : isStr(p.text) ? p.text : '';
+ const summary = raw.trim().slice(0, 120).trim();
+ lines.push(summary ? `- ${ing.name}: ${summary}` : `- ${ing.name}`);
+ }
+ }
+ const composed = lines.join('\n');
+ if (composed.length <= SEED_MAX) return composed;
+ 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) {
+ const list = (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);
+}
+
// Steps the importer actually pre-fills, so they open "ready" for review on an
// import-mode session. `idea` (universe + series exist), `plotArc` (arc +
// seasons), `characters` (extracted canon), and `issues` (the issue split) are
@@ -208,8 +264,21 @@ export async function createStorySession(input = {}) {
let universeId = trimTo(input.universeId, 64) || null;
let seriesId = trimTo(input.seriesId, 64) || null;
+ // Seed used to mint the shells: the user's seedIdea, or — when they picked
+ // Catalog ingredients but typed no seed — a fallback composed from those
+ // ingredients (#1761). In the normal (no-ingredients) case this equals
+ // seedIdea, so the create path is byte-for-byte unchanged.
+ let effectiveSeed = seedIdea;
if (intakeMode === 'seed') {
+ // Resolve any selected catalog ingredients up front: they feed both the
+ // fallback seed (so the minted shells aren't empty) and the series links
+ // created once the series exists. Missing/deleted ids are skipped.
+ const ingredients = await resolveCatalogIngredients(input.catalogIngredientIds);
+ if (!effectiveSeed && ingredients.length > 0) {
+ effectiveSeed = composeSeedFromIngredients(ingredients);
+ }
+
// Mint the shells the wizard fills in. The universe name doubles as the
// working title; the seed idea seeds the universe starter prompt.
//
@@ -220,12 +289,12 @@ export async function createStorySession(input = {}) {
// touch a universe the caller passed in (`input.universeId`).
let mintedUniverseId = null;
if (!universeId) {
- const universe = await createUniverse({ name: title, starterPrompt: seedIdea || '' });
+ const universe = await createUniverse({ name: title, starterPrompt: effectiveSeed || '' });
universeId = universe.id;
mintedUniverseId = universe.id;
}
if (!seriesId) {
- const series = await createSeries({ name: title, universeId, premise: seedIdea || '' }).catch(async (err) => {
+ const series = await createSeries({ name: title, universeId, premise: effectiveSeed || '' }).catch(async (err) => {
if (mintedUniverseId) {
// Roll back the just-created universe so a failed session create
// doesn't leave a stray (and already peer-subscribed) shell behind.
@@ -237,6 +306,14 @@ export async function createStorySession(input = {}) {
});
seriesId = series.id;
}
+
+ // Link the resolved ingredients to the (now-existing) series via
+ // catalog_ingredient_refs — the convergence contract's single data model.
+ // Role maps from the ingredient type; unknown types link as 'mentioned'.
+ if (ingredients.length > 0) {
+ const linked = await linkIngredientsToSeries(seriesId, ingredients);
+ console.log(`🔗 StoryBuilder: linked ${linked.length} catalog ingredient(s) to series ${seriesId}`);
+ }
}
const now = nowIso();
diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.js
index c53caa1805..5d7744b6d7 100644
--- a/server/services/storyBuilder.test.js
+++ b/server/services/storyBuilder.test.js
@@ -29,6 +29,16 @@ vi.mock('../lib/stageRunner.js', () => ({
extractJson: (raw) => JSON.parse(raw),
}));
+// catalogDB is Postgres-backed — mock it so the service test never touches the
+// 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(),
+}));
+vi.mock('./catalogDB.js', () => catalogMocks);
+
const sb = await import('./storyBuilder.js');
const seriesSvc = await import('./pipeline/series.js');
const universeSvc = await import('./universeBuilder.js');
@@ -38,6 +48,13 @@ beforeEach(() => {
fileStore.clear();
uuidCounter = 0;
stageRunnerSpy = undefined;
+ catalogMocks.listIngredients.mockReset();
+ catalogMocks.linkIngredientsToSeries.mockReset();
+ // Default: the batch resolve returns nothing (each test overrides as needed),
+ // and the batch link echoes back the ingredients it was handed.
+ catalogMocks.listIngredients.mockResolvedValue({ items: [] });
+ catalogMocks.linkIngredientsToSeries.mockImplementation(async (_seriesId, ings) =>
+ (Array.isArray(ings) ? ings.filter((i) => i && i.id) : []));
});
describe('storyBuilder — CRUD', () => {
@@ -116,6 +133,111 @@ describe('storyBuilder — CRUD', () => {
});
});
+describe('storyBuilder — catalog ingredient linking (#1761)', () => {
+ it('is a no-op when catalogIngredientIds is absent (back-compat)', async () => {
+ await sb.createStorySession({ title: 'Plain', seedIdea: 'a seed' });
+ expect(catalogMocks.listIngredients).not.toHaveBeenCalled();
+ expect(catalogMocks.linkIngredientsToSeries).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op for an empty catalogIngredientIds array', async () => {
+ await sb.createStorySession({ title: 'Plain', seedIdea: 'a seed', catalogIngredientIds: [] });
+ expect(catalogMocks.listIngredients).not.toHaveBeenCalled();
+ expect(catalogMocks.linkIngredientsToSeries).not.toHaveBeenCalled();
+ });
+
+ it('batch-resolves the ids and delegates linking in pick order', async () => {
+ const items = [
+ { id: 'cat-c', type: 'character', name: 'Mira', payload: {} },
+ { id: 'cat-p', type: 'place', name: 'Foundry', payload: {} },
+ { id: 'cat-o', type: 'object', name: 'Key', payload: {} },
+ { id: 'cat-x', type: 'scene', name: 'Opening', payload: {} },
+ ];
+ // Return the batch out of order to prove the resolver restores pick order.
+ catalogMocks.listIngredients.mockResolvedValue({ items: [items[2], items[0], items[3], items[1]] });
+
+ const s = await sb.createStorySession({
+ title: 'Linked', seedIdea: 'seed',
+ catalogIngredientIds: ['cat-c', 'cat-p', 'cat-o', 'cat-x'],
+ });
+
+ // ONE batch query (not N getIngredient round-trips).
+ expect(catalogMocks.listIngredients).toHaveBeenCalledTimes(1);
+ expect(catalogMocks.listIngredients).toHaveBeenCalledWith({ ids: ['cat-c', 'cat-p', 'cat-o', 'cat-x'], limit: 4 });
+ // ONE batch link with the resolved ingredients in the user's pick order.
+ expect(catalogMocks.linkIngredientsToSeries).toHaveBeenCalledTimes(1);
+ expect(catalogMocks.linkIngredientsToSeries).toHaveBeenCalledWith(s.seriesId, items);
+ });
+
+ it('skips ids the batch omits (missing / soft-deleted) without throwing', async () => {
+ // listIngredients already excludes soft-deleted rows, so the batch only
+ // returns the live one — the resolver drops the absent ids.
+ catalogMocks.listIngredients.mockResolvedValue({
+ items: [{ id: 'cat-live', type: 'character', name: 'Live', payload: {} }],
+ });
+
+ const s = await sb.createStorySession({
+ title: 'Sparse', seedIdea: 'seed',
+ catalogIngredientIds: ['cat-live', 'cat-dead', 'cat-missing'],
+ });
+
+ expect(catalogMocks.linkIngredientsToSeries).toHaveBeenCalledTimes(1);
+ expect(catalogMocks.linkIngredientsToSeries).toHaveBeenCalledWith(s.seriesId, [
+ { id: 'cat-live', type: 'character', name: 'Live', payload: {} },
+ ]);
+ });
+
+ it('composes a fallback seed from ingredients when seedIdea is blank', async () => {
+ catalogMocks.listIngredients.mockResolvedValue({ items: [
+ { id: 'cat-c', type: 'character', name: 'Mira', payload: { description: 'A weary foundry foreman.' } },
+ { id: 'cat-p', type: 'place', name: 'Foundry', payload: { summary: 'A silent ironworks.' } },
+ ] });
+
+ const s = await sb.createStorySession({
+ title: 'Composed', // no seedIdea
+ catalogIngredientIds: ['cat-c', 'cat-p'],
+ });
+
+ const series = await seriesSvc.getSeries(s.seriesId);
+ const universe = await universeSvc.getUniverse(s.universeId);
+ expect(series.premise).toContain('Characters:');
+ expect(series.premise).toContain('- Mira: A weary foundry foreman.');
+ expect(series.premise).toContain('Places:');
+ expect(series.premise).toContain('- Foundry: A silent ironworks.');
+ // The same composed seed feeds the universe starter prompt.
+ expect(universe.starterPrompt).toBe(series.premise);
+ // The user-facing seedIdea on the session stays the (empty) original.
+ expect(s.seedIdea).toBe('');
+ });
+
+ it('keeps the user seedIdea when one is provided (no fallback compose)', async () => {
+ const ing = { id: 'cat-c', type: 'character', name: 'Mira', payload: { description: 'desc' } };
+ catalogMocks.listIngredients.mockResolvedValue({ items: [ing] });
+
+ const s = await sb.createStorySession({
+ title: 'WithSeed', seedIdea: 'the foundry goes silent',
+ catalogIngredientIds: ['cat-c'],
+ });
+
+ const series = await seriesSvc.getSeries(s.seriesId);
+ expect(series.premise).toBe('the foundry goes silent');
+ // Still links the ingredient.
+ expect(catalogMocks.linkIngredientsToSeries).toHaveBeenCalledWith(s.seriesId, [ing]);
+ });
+
+ it('does not link in import mode', async () => {
+ const universe = await universeSvc.createUniverse({ name: 'U' });
+ const series = await seriesSvc.createSeries({ name: 'S', universeId: universe.id });
+ await sb.createStorySession({
+ title: 'Imported', intakeMode: 'import',
+ universeId: universe.id, seriesId: series.id,
+ catalogIngredientIds: ['cat-c'],
+ });
+ expect(catalogMocks.listIngredients).not.toHaveBeenCalled();
+ expect(catalogMocks.linkIngredientsToSeries).not.toHaveBeenCalled();
+ });
+});
+
describe('storyBuilder — lock state machine + gating', () => {
it('lockStep stamps an upstreamHash and flips status to locked', async () => {
const s = await sb.createStorySession({ title: 'X', seedIdea: 'seed' });