Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(casting): per-cast-member reference library (variants, tags, render guides) (#12762)

[._.]/c16dd8731a5c
diff --git a/client/src/components/catalog/CatalogReferenceLibrary.jsx b/client/src/components/catalog/CatalogReferenceLibrary.jsx
new file mode 100644
index 0000000000..53b6759e0b
--- /dev/null
+++ b/client/src/components/catalog/CatalogReferenceLibrary.jsx
@@ -0,0 +1,141 @@
+import { useMemo, useState } from 'react';
+import { Compass, Star } from 'lucide-react';
+import { updateCatalogIngredientMediaLibrary, attachCatalogIngredientMediaFromMoodBoard } from '../../services/apiCatalog';
+
+// Casting reference library: tag each reference/sheet/still/clip of a cast
+// member with the variant it shows (age, era, look) plus tags, mark up to four
+// as render guides, and filter the library by those fields. The media grid
+// below still owns attach/upload/detach/portrait.
+export const MAX_CAST_GUIDES = 4;
+const ERAS = ['child', 'teen', 'adult', 'elder'];
+const LIBRARY_KINDS = new Set(['portrait', 'reference', 'video']);
+const eraFor = (m) => m.library?.variant?.era
+ || (Number.isInteger(m.library?.variant?.age) ? (m.library.variant.age < 13 ? 'child' : m.library.variant.age < 20 ? 'teen' : m.library.variant.age < 65 ? 'adult' : 'elder') : '');
+
+export default function CatalogReferenceLibrary({ ingredientId, media = [], readOnly = false, onChanged }) {
+ const [filter, setFilter] = useState({ age: '', era: '', tag: '', guides: false });
+ const [error, setError] = useState('');
+ const [busyKey, setBusyKey] = useState('');
+ const [boardId, setBoardId] = useState('');
+ const [itemIds, setItemIds] = useState('');
+
+ const rows = useMemo(() => media.filter((m) => !m.deleted && LIBRARY_KINDS.has(m.kind)), [media]);
+ const guideCount = rows.filter((m) => m.library?.guide === true).length;
+ const ages = [...new Set(rows.map((m) => m.library?.variant?.age).filter(Number.isInteger))].sort((a, b) => a - b);
+ const tags = [...new Set(rows.flatMap((m) => m.library?.tags || []))].sort();
+ const visible = rows.filter((m) => (filter.age === '' || m.library?.variant?.age === Number(filter.age))
+ && (!filter.era || eraFor(m) === filter.era)
+ && (!filter.tag || (m.library?.tags || []).includes(filter.tag))
+ && (!filter.guides || m.library?.guide === true));
+
+ const save = async (m, patch) => {
+ setError('');
+ setBusyKey(`${m.kind}:${m.mediaKey}`);
+ try {
+ await updateCatalogIngredientMediaLibrary(ingredientId, { mediaKey: m.mediaKey, kind: m.kind, ...patch });
+ onChanged?.();
+ } catch (err) {
+ setError(err?.message || 'Could not update reference');
+ } finally {
+ setBusyKey('');
+ }
+ };
+
+ const importBoard = async () => {
+ const ids = itemIds.split(/[\s,]+/).filter(Boolean);
+ if (!boardId.trim() || ids.length === 0) return;
+ setError('');
+ try {
+ await attachCatalogIngredientMediaFromMoodBoard(ingredientId, { boardId: boardId.trim(), itemIds: ids, inferAge: true });
+ setItemIds('');
+ onChanged?.();
+ } catch (err) {
+ setError(err?.message || 'Could not import from mood board');
+ }
+ };
+
+ return (
+ <section aria-label="Reference library" className="space-y-3 rounded border border-port-border p-3">
+ <header className="flex flex-wrap items-center gap-2 text-sm">
+ <h3 className="font-semibold">Reference library</h3>
+ <span data-testid="guide-count" className="text-gray-400">{guideCount}/{MAX_CAST_GUIDES} render guides</span>
+ <label className="ml-auto flex items-center gap-1">Age
+ <select aria-label="Filter by age" value={filter.age} onChange={(e) => setFilter({ ...filter, age: e.target.value })} className="bg-port-card">
+ <option value="">All</option>
+ {ages.map((a) => <option key={a} value={a}>{a}</option>)}
+ </select>
+ </label>
+ <label className="flex items-center gap-1">Era
+ <select aria-label="Filter by era" value={filter.era} onChange={(e) => setFilter({ ...filter, era: e.target.value })} className="bg-port-card">
+ <option value="">All</option>
+ {ERAS.map((era) => <option key={era} value={era}>{era}</option>)}
+ </select>
+ </label>
+ {tags.length > 0 && (
+ <label className="flex items-center gap-1">Tag
+ <select aria-label="Filter by tag" value={filter.tag} onChange={(e) => setFilter({ ...filter, tag: e.target.value })} className="bg-port-card">
+ <option value="">All</option>
+ {tags.map((t) => <option key={t} value={t}>{t}</option>)}
+ </select>
+ </label>
+ )}
+ <label className="flex items-center gap-1">
+ <input type="checkbox" checked={filter.guides} onChange={(e) => setFilter({ ...filter, guides: e.target.checked })} /> Guides only
+ </label>
+ </header>
+ {error && <p role="alert" className="text-sm text-port-error">{error}</p>}
+ {visible.length === 0 ? <p className="text-sm text-gray-400">No references match.</p> : (
+ <ul className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
+ {visible.map((m) => {
+ const key = `${m.kind}:${m.mediaKey}`;
+ const lib = m.library || {};
+ const isGuide = lib.guide === true;
+ const busy = busyKey === key;
+ return (
+ <li key={key} data-testid="library-row" className="space-y-1 rounded bg-port-card p-2 text-xs">
+ <div className="flex items-center gap-1">
+ {m.kind === 'portrait' && <Star size={12} aria-label="Primary" />}
+ <span className="truncate" title={m.mediaKey}>{lib.variant?.label || m.caption || m.mediaKey}</span>
+ <span className="ml-auto text-gray-500">{m.kind}</span>
+ </div>
+ {!readOnly && (
+ <div className="flex flex-wrap items-center gap-1">
+ <input aria-label={`Age for ${m.mediaKey}`} type="number" min="0" max="150" defaultValue={lib.variant?.age ?? ''} className="w-14 bg-port-bg"
+ onBlur={(e) => {
+ const age = e.target.value === '' ? undefined : Number(e.target.value);
+ if (age !== lib.variant?.age) save(m, { variant: { ...(lib.variant || {}), age } });
+ }} />
+ <select aria-label={`Era for ${m.mediaKey}`} value={lib.variant?.era || ''} className="bg-port-bg"
+ onChange={(e) => save(m, { variant: { ...(lib.variant || {}), era: e.target.value || undefined } })}>
+ <option value="">era</option>
+ {ERAS.map((era) => <option key={era} value={era}>{era}</option>)}
+ </select>
+ <input aria-label={`Tags for ${m.mediaKey}`} defaultValue={(lib.tags || []).join(', ')} placeholder="tags" className="w-24 bg-port-bg"
+ onBlur={(e) => {
+ const next = e.target.value.split(',').map((t) => t.trim()).filter(Boolean);
+ if (next.join(',') !== (lib.tags || []).join(',')) save(m, { tags: next });
+ }} />
+ {m.kind !== 'video' && (
+ <button type="button" disabled={busy || (!isGuide && guideCount >= MAX_CAST_GUIDES)} aria-pressed={isGuide}
+ title={!isGuide && guideCount >= MAX_CAST_GUIDES ? `At most ${MAX_CAST_GUIDES} render guides` : 'Use as a render guide'}
+ onClick={() => save(m, { guide: !isGuide })} className="flex items-center gap-1">
+ <Compass size={12} /> {isGuide ? 'Guide' : 'Make guide'}
+ </button>
+ )}
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ {!readOnly && (
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <input aria-label="Mood board id" value={boardId} onChange={(e) => setBoardId(e.target.value)} placeholder="mood board id" className="bg-port-bg" />
+ <input aria-label="Mood board item ids" value={itemIds} onChange={(e) => setItemIds(e.target.value)} placeholder="item ids (comma separated)" className="min-w-[12rem] flex-1 bg-port-bg" />
+ <button type="button" onClick={importBoard}>Add from mood board</button>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/catalog/CatalogReferenceLibrary.test.jsx b/client/src/components/catalog/CatalogReferenceLibrary.test.jsx
new file mode 100644
index 0000000000..815f18d1b2
--- /dev/null
+++ b/client/src/components/catalog/CatalogReferenceLibrary.test.jsx
@@ -0,0 +1,59 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+
+vi.mock('../../services/apiCatalog', () => ({
+ updateCatalogIngredientMediaLibrary: vi.fn(async () => ({})),
+ attachCatalogIngredientMediaFromMoodBoard: vi.fn(async () => ({ attached: [], skipped: [] })),
+}));
+const api = await import('../../services/apiCatalog');
+const { default: CatalogReferenceLibrary } = await import('./CatalogReferenceLibrary.jsx');
+
+const media = [
+ { mediaKey: 'seven.png', kind: 'reference', library: { variant: { age: 7 }, guide: true, tags: ['vhs'] } },
+ { mediaKey: 'seventeen.png', kind: 'reference', library: { variant: { age: 17 } } },
+ { mediaKey: 'clip.mp4', kind: 'video', library: { variant: { age: 27 } } },
+ { mediaKey: 'voice.m4a', kind: 'audio', library: {} },
+];
+
+describe('CatalogReferenceLibrary', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('lists image/video references, counts guides and filters by age and era', () => {
+ render(<CatalogReferenceLibrary ingredientId="cat-chr-1" media={media} />);
+ expect(screen.getAllByTestId('library-row')).toHaveLength(3);
+ expect(screen.getByTestId('guide-count').textContent).toContain('1/4');
+ fireEvent.change(screen.getByLabelText('Filter by age'), { target: { value: '17' } });
+ expect(screen.getAllByTestId('library-row')).toHaveLength(1);
+ fireEvent.change(screen.getByLabelText('Filter by age'), { target: { value: '' } });
+ fireEvent.change(screen.getByLabelText('Filter by era'), { target: { value: 'adult' } });
+ expect(screen.getAllByTestId('library-row')).toHaveLength(1);
+ });
+
+ it('toggles a guide through the library API and refreshes', async () => {
+ const onChanged = vi.fn();
+ render(<CatalogReferenceLibrary ingredientId="cat-chr-1" media={media} onChanged={onChanged} />);
+ fireEvent.click(screen.getByRole('button', { name: /make guide/i }));
+ await waitFor(() => expect(onChanged).toHaveBeenCalled());
+ expect(api.updateCatalogIngredientMediaLibrary).toHaveBeenCalledWith('cat-chr-1', { mediaKey: 'seventeen.png', kind: 'reference', guide: true });
+ });
+
+ it('disables new guides at the cap of four', () => {
+ const full = [1, 2, 3, 4, 5].map((n) => ({ mediaKey: `${n}.png`, kind: 'reference', library: { guide: n <= 4 } }));
+ render(<CatalogReferenceLibrary ingredientId="cat-chr-1" media={full} />);
+ expect(screen.getByRole('button', { name: /make guide/i }).disabled).toBe(true);
+ });
+
+ it('imports mood board items with age inference', async () => {
+ render(<CatalogReferenceLibrary ingredientId="cat-chr-1" media={[]} />);
+ fireEvent.change(screen.getByLabelText('Mood board id'), { target: { value: 'mb-1' } });
+ fireEvent.change(screen.getByLabelText('Mood board item ids'), { target: { value: 'a, b' } });
+ fireEvent.click(screen.getByRole('button', { name: /add from mood board/i }));
+ await waitFor(() => expect(api.attachCatalogIngredientMediaFromMoodBoard)
+ .toHaveBeenCalledWith('cat-chr-1', { boardId: 'mb-1', itemIds: ['a', 'b'], inferAge: true }));
+ });
+
+ it('hides editing controls when read-only', () => {
+ render(<CatalogReferenceLibrary ingredientId="cat-chr-1" media={media} readOnly />);
+ expect(screen.queryByRole('button', { name: /guide/i })).toBeNull();
+ });
+});
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 3b7f70467c..56ad9f1707 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -7,6 +7,7 @@
* unsaved draft. Full-width page; owns its scroll.
*/
+import CatalogReferenceLibrary from '../components/catalog/CatalogReferenceLibrary.jsx';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams, useLocation, Link } from 'react-router';
import { Sparkles, Save, Trash2, ArrowLeft, Loader2, Plus, X, History, RotateCcw, Image as ImageIcon, ChevronDown, Upload, Mic, Square, UserRound, LayoutGrid, Images, Clapperboard, Shirt } from 'lucide-react';
@@ -866,6 +867,10 @@ function IngredientEditor() {
/>
)}
+ {activeTab === 'references' && record.type === 'character' && (
+ <CatalogReferenceLibrary ingredientId={record.id} media={media} readOnly={identityReadOnly} onChanged={refreshMedia} />
+ )}
+
{(activeTab === 'profile' ? !tabs : activeTab === 'references' || activeTab === 'images') && (
<MediaPanel
readOnly={identityReadOnly}
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index 0d982e8bfd..16c3c630a9 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -235,3 +235,10 @@ export const getCatalogMergeReceipt = (id, options) =>
request(`/catalog/ingredient-merges/${enc(id)}`, options);
export const recoverCatalogMerge = (id, options) =>
request(`/catalog/ingredient-merges/${enc(id)}/recover`, { method: 'POST', body: '{}', ...options });
+
+// --- Casting reference library (variant / tags / render-guide flag) ---
+export const updateCatalogIngredientMediaLibrary = (id, body, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media/library`, { method: 'PATCH', body: JSON.stringify(body), ...options });
+
+export const attachCatalogIngredientMediaFromMoodBoard = (id, body, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media/from-mood-board`, { method: 'POST', body: JSON.stringify(body), ...options });
diff --git a/scripts/migrations/434-catalog-media-reference-library.js b/scripts/migrations/434-catalog-media-reference-library.js
new file mode 100644
index 0000000000..693f2b1790
--- /dev/null
+++ b/scripts/migrations/434-catalog-media-reference-library.js
@@ -0,0 +1,20 @@
+/**
+ * Registration stub for the Casting reference library: the
+ * `catalog_ingredient_media.library` JSONB column (variant age/era/wardrobe,
+ * tags, render-guide flag).
+ *
+ * Like 052, the DDL lives in `ensureSchema()` (server/lib/db/schema/catalog.js)
+ * and `server/scripts/init-db.sql`, because this runner executes before the DB
+ * pool exists. ensureSchema also performs the one-time seeding, gated on the
+ * presence of its INPUT (existing portrait / sheet media rows whose `library`
+ * is still empty): portraits become render guides, sheet rows get their sheet
+ * role as the variant label, and `look:<wardrobeId>` rows get that wardrobe.
+ * A row the user already edited has a non-empty `library` and is never
+ * touched again. No data.reference seed ships.
+ */
+
+export default {
+ async up() {
+ console.log('🎭 catalog_ingredient_media.library: column + seeding applied idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index dc353a9d4a..e51a41f0d2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -135,6 +135,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `catalogExtractionDraft.js` | Extraction-only six-type graph schema, strict grounded-output parsing, and conservative chunk identity/edge reconciliation. |
| `catalogIdentityValidation.js` | Bilateral canonical catalog identity operator and peer evidence schemas. |
| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |
+| `catalogMediaLibrary.js` | Casting reference library helpers: normalize variant/tags/guide, filter by age/era/look/tag, pick up to 4 render guides. |
| `cosValidation.js` | Chief-of-Staff task/job/loop/learning schemas, the Code-Review settings slice, and the task-metadata sanitizer. `createCosTaskSchema`'s metadata-bound fields are carried onto the task by `services/cosTaskIntake.js` (parity-checked by its test). The Review-Loop reviewer vocabulary lives in `reviewerConfig.js` (#5702) and is re-exported flat from here. |
| `creativeBriefLimits.js` | `COMMISSION_NAME_MAX` / `COMMISSION_INTENT_MAX` / `COMMISSION_STYLE_SPEC_MAX` / `COMMISSION_BRIEF_TAG_MAX` and `CREATIVE_DIRECTOR_GOAL_MAX` — the creative brief caps `creativeCommissionValidation.js` and `creativeDirectorValidation.js` enforce and the browser forms use as a silent input `maxLength`. A pure leaf (the schemas pull `zod`) so `client/src/components/creative-commission/commissionForm.js` and `client/src/lib/creativeDirectorPlan.js` re-export one definition instead of copying the numbers. |
| `creativeCommissionSpec.js` | `GENERATION_KEY_DEFS` / `ABILITY_GENERATION_SPEC` / `resolvedDefault` and the quality / aspect-ratio / image-mode / video-mode enums — the generation-param spec `creativeCommissionValidation.js` builds its Zod schema from and the ability adapters sanitize against. A pure leaf (like `creativeBriefLimits.js`) so `client/src/components/creative-commission/commissionForm.js` derives its fields/bounds/defaults from it directly instead of hand-copying them (#6816). |
diff --git a/server/lib/catalogMediaLibrary.js b/server/lib/catalogMediaLibrary.js
new file mode 100644
index 0000000000..5ec7f8f4d0
--- /dev/null
+++ b/server/lib/catalogMediaLibrary.js
@@ -0,0 +1,113 @@
+/**
+ * Cast reference library (Casting > References).
+ *
+ * Each catalog media row carries an optional `library` JSONB describing how the
+ * asset is used as a reference for the cast member: which variant it depicts
+ * (age, era, wardrobe/look, free label), searchable tags, and whether it is a
+ * render GUIDE — one of at most MAX_CAST_GUIDES images that conditioning picks
+ * from. The primary image stays the existing single `portrait` row.
+ *
+ * Pure helpers only (no DB) so the picker is shared by routes, music video
+ * conditioning and tests.
+ */
+
+export const MAX_CAST_GUIDES = 4;
+export const CAST_ERAS = Object.freeze(['child', 'teen', 'adult', 'elder']);
+export const MAX_LIBRARY_TAGS = 20;
+
+const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
+const cleanStr = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : undefined);
+
+// Era a bare age falls into when the asset was not tagged with one.
+function eraForAge(age) {
+ if (!Number.isFinite(age)) return undefined;
+ if (age < 13) return 'child';
+ if (age < 20) return 'teen';
+ if (age < 65) return 'adult';
+ return 'elder';
+}
+
+/** Normalize a stored/peer `library` value into its canonical shape. */
+export function normalizeLibrary(value) {
+ if (!isObj(value)) return {};
+ const out = {};
+ const variant = isObj(value.variant) ? value.variant : {};
+ const v = {};
+ if (Number.isInteger(variant.age) && variant.age >= 0 && variant.age <= 150) v.age = variant.age;
+ if (CAST_ERAS.includes(variant.era)) v.era = variant.era;
+ const wardrobeId = cleanStr(variant.wardrobeId, 59);
+ if (wardrobeId) v.wardrobeId = wardrobeId;
+ const label = cleanStr(variant.label, 120);
+ if (label) v.label = label;
+ if (Object.keys(v).length) out.variant = v;
+ if (Array.isArray(value.tags)) {
+ const tags = [...new Set(value.tags.map((t) => cleanStr(t, 40)?.toLowerCase()).filter(Boolean))].slice(0, MAX_LIBRARY_TAGS);
+ if (tags.length) out.tags = tags;
+ }
+ if (typeof value.guide === 'boolean') out.guide = value.guide;
+ return out;
+}
+
+const mediaEra = (m) => m?.library?.variant?.era || eraForAge(m?.library?.variant?.age);
+
+/** Filter live media rows by `{ age, era, wardrobeId, tag, kind, guide }`. */
+export function filterLibraryMedia(media, filters = {}) {
+ const list = Array.isArray(media) ? media : [];
+ return list.filter((m) => {
+ if (!m || m.deleted) return false;
+ const lib = m.library || {};
+ if (filters.kind && m.kind !== filters.kind) return false;
+ if (Number.isInteger(filters.age) && lib.variant?.age !== filters.age) return false;
+ if (filters.era && mediaEra(m) !== filters.era) return false;
+ if (filters.wardrobeId && lib.variant?.wardrobeId !== filters.wardrobeId) return false;
+ if (filters.tag && !(lib.tags || []).includes(String(filters.tag).toLowerCase())) return false;
+ if (filters.guide === true && lib.guide !== true) return false;
+ return true;
+ });
+}
+
+const IMAGE_KINDS = new Set(['portrait', 'reference']);
+
+function score(m, want) {
+ const v = m.library?.variant || {};
+ let s = 0;
+ if (Number.isInteger(want.age) && Number.isInteger(v.age)) s += Math.max(0, 60 - 2 * Math.abs(v.age - want.age));
+ const wantEra = want.era || eraForAge(want.age);
+ if (wantEra && mediaEra(m) === wantEra) s += 30;
+ if (want.wardrobeId && v.wardrobeId === want.wardrobeId) s += 20;
+ if (m.library?.guide) s += 10;
+ if (m.kind === 'portrait') s += 5;
+ return s;
+}
+
+/**
+ * Pick up to `cap` image references to condition a render of this cast member.
+ * Guides are preferred; when none are flagged the portrait then newest
+ * references stand in. Within a pool, the closest variant (age → era →
+ * wardrobe) wins, then the portrait, then newest. Videos never condition.
+ */
+export function pickGuideMedia(media, want = {}, cap = MAX_CAST_GUIDES) {
+ const images = (Array.isArray(media) ? media : []).filter((m) => m && !m.deleted && IMAGE_KINDS.has(m.kind));
+ const guides = images.filter((m) => m.library?.guide === true);
+ const pool = guides.length ? guides : images;
+ const time = (m) => Date.parse(m.createdAt || 0) || 0;
+ return [...pool]
+ .sort((a, b) => score(b, want) - score(a, want) || time(b) - time(a))
+ .slice(0, Math.max(0, Math.min(cap, MAX_CAST_GUIDES)));
+}
+
+/** Strip a mood-board/media-history `image:`/`video:` key to library kind + filename. */
+export function parseLibraryMediaKey(key) {
+ if (typeof key !== 'string') return null;
+ const m = /^(image|video):(.+)$/.exec(key.trim());
+ if (!m || !m[2] || m[2].includes('..') || m[2].startsWith('/')) return null;
+ return { kind: m[1] === 'video' ? 'video' : 'reference', mediaKey: m[2] };
+}
+
+/** Best-effort age read from a caption like "Nora at 17" / "age 7" / "(27)". */
+export function inferAgeFromText(text) {
+ if (typeof text !== 'string') return undefined;
+ const m = /\b(?:age[sd]?\s*|at\s+)(\d{1,3})\b/i.exec(text);
+ const age = m ? Number(m[1]) : NaN;
+ return Number.isInteger(age) && age <= 150 ? age : undefined;
+}
diff --git a/server/lib/catalogMediaLibrary.test.js b/server/lib/catalogMediaLibrary.test.js
new file mode 100644
index 0000000000..0061268624
--- /dev/null
+++ b/server/lib/catalogMediaLibrary.test.js
@@ -0,0 +1,73 @@
+import { describe, it, expect } from 'vitest';
+import {
+ MAX_CAST_GUIDES, normalizeLibrary, filterLibraryMedia, pickGuideMedia,
+ parseLibraryMediaKey, inferAgeFromText,
+} from './catalogMediaLibrary.js';
+
+const row = (mediaKey, kind, library = {}, createdAt = '2026-01-01T00:00:00.000Z') => ({ mediaKey, kind, library, createdAt });
+
+describe('catalogMediaLibrary', () => {
+ it('derives eras from ages when filtering', () => {
+ const media = [7, 17, 27, 70].map((age) => row(`${age}.png`, 'reference', { variant: { age } }));
+ expect(['child', 'teen', 'adult', 'elder'].map((era) => filterLibraryMedia(media, { era })[0].mediaKey))
+ .toEqual(['7.png', '17.png', '27.png', '70.png']);
+ });
+
+ it('normalizes library values and drops junk', () => {
+ expect(normalizeLibrary(null)).toEqual({});
+ expect(normalizeLibrary({ variant: { age: 7.5, era: 'nope', label: ' age 7 ' }, tags: ['VHS', 'vhs', ' ', 3], guide: 'yes' }))
+ .toEqual({ variant: { label: 'age 7' }, tags: ['vhs'] });
+ expect(normalizeLibrary({ variant: { age: 17, era: 'teen', wardrobeId: 'w1' }, guide: true }))
+ .toEqual({ variant: { age: 17, era: 'teen', wardrobeId: 'w1' }, guide: true });
+ });
+
+ it('filters by age, era (derived), tag, kind and guide', () => {
+ const media = [
+ row('a.png', 'reference', { variant: { age: 7 }, tags: ['vhs'] }),
+ row('b.png', 'reference', { variant: { era: 'adult' }, guide: true }),
+ row('c.mp4', 'video', { variant: { age: 17 } }),
+ { ...row('d.png', 'reference', { variant: { age: 7 } }), deleted: true },
+ ];
+ expect(filterLibraryMedia(media, { age: 7 }).map((m) => m.mediaKey)).toEqual(['a.png']);
+ expect(filterLibraryMedia(media, { era: 'teen' }).map((m) => m.mediaKey)).toEqual(['c.mp4']);
+ expect(filterLibraryMedia(media, { tag: 'VHS' }).map((m) => m.mediaKey)).toEqual(['a.png']);
+ expect(filterLibraryMedia(media, { kind: 'video' }).map((m) => m.mediaKey)).toEqual(['c.mp4']);
+ expect(filterLibraryMedia(media, { guide: true }).map((m) => m.mediaKey)).toEqual(['b.png']);
+ });
+
+ it('prefers guides matching the requested age, never videos, capped at 4', () => {
+ const media = [
+ row('adult.png', 'reference', { variant: { age: 27 }, guide: true }),
+ row('child.png', 'reference', { variant: { age: 7 }, guide: true }),
+ row('teen.png', 'reference', { variant: { age: 17 }, guide: true }),
+ row('unflagged-child.png', 'reference', { variant: { age: 7 } }),
+ row('clip.mp4', 'video', { variant: { age: 7 }, guide: true }),
+ ];
+ expect(pickGuideMedia(media, { age: 7 }).map((m) => m.mediaKey)).toEqual(['child.png', 'teen.png', 'adult.png']);
+ expect(pickGuideMedia(media, { age: 27 }, 1).map((m) => m.mediaKey)).toEqual(['adult.png']);
+ expect(pickGuideMedia(media, {}, 99)).toHaveLength(3);
+ expect(MAX_CAST_GUIDES).toBe(4);
+ });
+
+ it('falls back to portrait then newest when nothing is a guide', () => {
+ const media = [
+ row('old.png', 'reference', {}, '2026-01-01T00:00:00.000Z'),
+ row('new.png', 'reference', {}, '2026-02-01T00:00:00.000Z'),
+ row('face.png', 'portrait', {}, '2025-01-01T00:00:00.000Z'),
+ ];
+ expect(pickGuideMedia(media).map((m) => m.mediaKey)).toEqual(['face.png', 'new.png', 'old.png']);
+ });
+
+ it('parses typed media keys safely', () => {
+ expect(parseLibraryMediaKey('image:a.png')).toEqual({ kind: 'reference', mediaKey: 'a.png' });
+ expect(parseLibraryMediaKey('video:b.mp4')).toEqual({ kind: 'video', mediaKey: 'b.mp4' });
+ expect(parseLibraryMediaKey('image:../x.png')).toBeNull();
+ expect(parseLibraryMediaKey('a.png')).toBeNull();
+ });
+
+ it('infers ages from captions', () => {
+ expect(inferAgeFromText('Experiment ages: Nora at 17, VHS')).toBe(17);
+ expect(inferAgeFromText('reference sheet, age 7')).toBe(7);
+ expect(inferAgeFromText('no age here')).toBeUndefined();
+ });
+});
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index b59725aad4..b99a335504 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -377,6 +377,39 @@ export const catalogMediaAttachSchema = z.object({
caption: z.string().trim().max(2_000).optional().nullable(),
}).strict();
+// Casting reference library patch (#casting-reference-library). Identifies a
+// live media row by (mediaKey, kind) and merges any of variant/tags/guide.
+export const catalogMediaLibraryVariantSchema = z.object({
+ age: z.number().int().min(0).max(150).optional(),
+ era: z.enum(['child', 'teen', 'adult', 'elder']).optional(),
+ wardrobeId: z.string().trim().min(1).max(59).optional(),
+ label: z.string().trim().max(120).optional(),
+}).strict();
+export const catalogMediaLibraryPatchSchema = z.object({
+ mediaKey: z.string().trim().min(1).max(512),
+ kind: z.enum(MEDIA_KINDS),
+ variant: catalogMediaLibraryVariantSchema.optional(),
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
+ guide: z.boolean().optional(),
+}).strict();
+// Attach mood-board items to a cast member as references, optionally tagging
+// them all with one variant (e.g. every age-7 sheet) and tags.
+export const catalogMediaFromMoodBoardSchema = z.object({
+ boardId: z.string().trim().min(1).max(64),
+ itemIds: z.array(z.string().trim().min(1).max(64)).min(1).max(100),
+ variant: catalogMediaLibraryVariantSchema.optional(),
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
+ inferAge: z.boolean().optional(),
+}).strict();
+export const catalogMediaLibraryQuerySchema = z.object({
+ age: z.coerce.number().int().min(0).max(150).optional(),
+ era: z.enum(['child', 'teen', 'adult', 'elder']).optional(),
+ wardrobeId: z.string().trim().min(1).max(59).optional(),
+ tag: z.string().trim().min(1).max(40).optional(),
+ kind: z.enum(MEDIA_KINDS).optional(),
+ guide: z.enum(['true', 'false']).optional(),
+}).strip();
+
// Set-portrait body — same as attach minus `kind` (the route forces 'portrait').
export const catalogPortraitSetSchema = z.object({
mediaKey: z.string().trim().min(1).max(512),
@@ -769,6 +802,8 @@ export const catalogSyncMediaSchema = z.object({
role: z.string().max(64).nullable().optional(),
caption: z.string().max(2_000).nullable().optional(),
metadata: catalogMediaMetadataSchema.optional(),
+ // catalog v12: Casting reference library (variant/tags/guide); normalized on apply.
+ library: z.object({}).passthrough().refine((v) => JSON.stringify(v).length <= 4096, { message: 'media library exceeds 4KB' }).optional(),
createdAt: isoDate,
deleted: z.boolean().optional(),
deletedAt: z.string().nullable().optional(),
diff --git a/server/lib/db/schema/catalog.js b/server/lib/db/schema/catalog.js
index 502ee5a1b7..f31b670c11 100644
--- a/server/lib/db/schema/catalog.js
+++ b/server/lib/db/schema/catalog.js
@@ -321,6 +321,16 @@ export const catalogDdl = [
`ALTER TABLE catalog_ingredient_media ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ`,
`UPDATE catalog_ingredient_media SET updated_at = COALESCE(deleted_at, created_at) WHERE updated_at IS NULL`,
`ALTER TABLE catalog_ingredient_media ALTER COLUMN updated_at SET DEFAULT NOW()`,
+ // Casting reference library (variant/tags/guide). Added nullable so the
+ // one-time seed below can tell pre-existing rows (NULL) from rows a user
+ // already edited; once backfilled to '{}' the seed is a no-op forever.
+ `ALTER TABLE catalog_ingredient_media ADD COLUMN IF NOT EXISTS library JSONB`,
+ `UPDATE catalog_ingredient_media SET library = '{"guide": true}'::jsonb WHERE library IS NULL AND kind = 'portrait' AND deleted = false`,
+ `UPDATE catalog_ingredient_media SET library = jsonb_build_object('variant', jsonb_build_object('wardrobeId', left(substring(role from 6), 59), 'label', left(role, 120))) WHERE library IS NULL AND role LIKE 'look:_%'`,
+ `UPDATE catalog_ingredient_media SET library = jsonb_build_object('variant', jsonb_build_object('label', left(role, 120))) WHERE library IS NULL AND kind = 'reference' AND role ILIKE '%sheet%'`,
+ `UPDATE catalog_ingredient_media SET library = '{}'::jsonb WHERE library IS NULL`,
+ `ALTER TABLE catalog_ingredient_media ALTER COLUMN library SET DEFAULT '{}'::jsonb`,
+ `ALTER TABLE catalog_ingredient_media ALTER COLUMN library SET NOT NULL`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_ingredient ON catalog_ingredient_media (ingredient_id)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_key ON catalog_ingredient_media (media_key)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_ing_media_sync_seq ON catalog_ingredient_media (sync_sequence)`,
@@ -477,7 +487,8 @@ export const catalogDdl = [
OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at
OR NEW.role IS DISTINCT FROM OLD.role
OR NEW.caption IS DISTINCT FROM OLD.caption
- OR NEW.metadata IS DISTINCT FROM OLD.metadata THEN
+ OR NEW.metadata IS DISTINCT FROM OLD.metadata
+ OR NEW.library IS DISTINCT FROM OLD.library THEN
IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
NEW.updated_at := catalog_next_change_clock(OLD.updated_at);
END IF;
diff --git a/server/lib/index.js b/server/lib/index.js
index ce5886530e..8eede914c4 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -39,6 +39,7 @@ export * from './brainThreads.js';
export * from './humanActions.js';
export * as catalogIdentityValidation from './catalogIdentityValidation.js';
export * as catalogValidation from './catalogValidation.js';
+export * as catalogMediaLibrary from './catalogMediaLibrary.js';
export * as characterAugmentValidation from './characterAugmentValidation.js';
export * as characterEvolutionValidation from './characterEvolutionValidation.js';
export * as cosValidation from './cosValidation.js';
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index d8b8946f08..5b49d4fb2f 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -425,7 +425,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// BOTH sides apply the guard. Tombstone-only transfers already skip the
// live-row equality check; a v11 receiver's guard still degrades safely
// for a ≤v10 sender's tombstone-less payload (unchanged "no opinion" path).
- catalog: 11,
+ // v12 = `catalog_ingredient_media.library` (Casting reference library:
+ // variant age/era/wardrobe, tags, render-guide flag). A ≤v11 receiver would
+ // drop it and whole-row LWW it back, so live transfers need equal versions.
+ catalog: 12,
// v1 = cross-machine resumable Story Builder sessions (#730). Sessions are
// local-only by default and excluded from sync; only `sync: true` sessions
// ride the `storyBuilder` snapshot category. This is a brand-NEW synced
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index 26a61335d2..ba3d9a9414 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -54,7 +54,7 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
it('version-gates catalog object attachments and media generation provenance', () => {
// v11 adds the ref/relation/media tombstone-revival guard (#8347).
- expect(PORTOS_SCHEMA_VERSIONS.catalog).toBe(11);
+ expect(PORTOS_SCHEMA_VERSIONS.catalog).toBe(12);
});
it('version-gates the persisted FableLoom shot and reference shape', () => {
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 26025c215f..a082aa4a31 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -19,6 +19,9 @@ import {
catalogIngredientLinkSchema,
catalogRelationLinkSchema,
catalogMediaAttachSchema,
+ catalogMediaLibraryPatchSchema,
+ catalogMediaFromMoodBoardSchema,
+ catalogMediaLibraryQuerySchema,
catalogMediaDetachSchema,
catalogMediaFileUploadSchema,
catalogMediaVoiceMemoSchema,
@@ -54,6 +57,8 @@ import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/em
import { extractIngredientsForScrap } from '../services/catalogExtraction.js';
import { ingestFromUrl, ingestFromFile, ingestFromVoice, ingestFromBrain } from '../services/catalogIngestSources.js';
import { readImageGenerationMetadata, uploadIngredientMediaFile, recordIngredientVoiceMemo } from '../services/catalogMedia.js';
+import { getBoard as getMoodBoard } from '../services/moodBoard/index.js';
+import { filterLibraryMedia, pickGuideMedia, parseLibraryMediaKey, inferAgeFromText } from '../lib/catalogMediaLibrary.js';
import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';
import { previewCatalogCastImport, commitCatalogCastImport } from '../services/musicVideo/catalogCast.js';
import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
@@ -537,7 +542,61 @@ const IMAGE_MEDIA_KINDS = new Set(['portrait', 'reference']);
router.get('/ingredients/:id/media', asyncHandler(async (req, res) => {
const ing = await catalogDB.getIngredient(req.params.id);
if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
- res.json(await catalogDB.listMediaForIngredient(req.params.id));
+ const filters = validateRequest(catalogMediaLibraryQuerySchema, req.query);
+ const media = await catalogDB.listMediaForIngredient(req.params.id);
+ // No filter = the unchanged full list; any filter narrows by the Casting library fields.
+ res.json(Object.keys(filters).length ? filterLibraryMedia(media, { ...filters, guide: filters.guide === 'true' ? true : undefined }) : media);
+}));
+
+// Casting reference library: the up-to-4 images a render of this cast member
+// should condition on for the requested variant (?age=&era=&wardrobeId=).
+router.get('/ingredients/:id/media/guides', asyncHandler(async (req, res) => {
+ const ing = await catalogDB.getIngredient(req.params.id);
+ if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
+ const want = validateRequest(catalogMediaLibraryQuerySchema, req.query);
+ res.json({ guides: pickGuideMedia(await catalogDB.listMediaForIngredient(req.params.id), want) });
+}));
+
+// Edit a media row's Casting library fields (variant/tags/guide). 409 past 4 guides.
+router.patch('/ingredients/:id/media/library', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogMediaLibraryPatchSchema, req.body);
+ const ing = await catalogDB.getIngredient(req.params.id);
+ if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
+ const { mediaKey, kind, ...patch } = body;
+ const media = await catalogDB.updateMediaLibrary(req.params.id, mediaKey, kind, patch).catch((err) => {
+ if (err?.status) throw new ServerError(err.message, { status: err.status });
+ throw err;
+ });
+ res.json(media);
+}));
+
+// Attach mood-board items (image:/video: keys) as references in one call,
+// tagging each with the given variant/tags (or an age read from its caption).
+router.post('/ingredients/:id/media/from-mood-board', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogMediaFromMoodBoardSchema, req.body);
+ const ing = await catalogDB.getIngredient(req.params.id);
+ if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
+ const board = await getMoodBoard(body.boardId);
+ if (!board) throw new ServerError('Mood board not found', { status: 404 });
+ const items = new Map((board.items || []).map((item) => [item.id, item]));
+ const attached = [];
+ const skipped = [];
+ for (const itemId of body.itemIds) {
+ const item = items.get(itemId);
+ const parsed = parseLibraryMediaKey(item?.mediaKey);
+ if (!parsed || (parsed.kind === 'reference' && !resolveImageInputPath(parsed.mediaKey))) { skipped.push(itemId); continue; }
+ const caption = typeof item.caption === 'string' ? item.caption.slice(0, 2000) : null;
+ const metadata = parsed.kind === 'reference' ? await readImageGenerationMetadata(parsed.mediaKey) : {};
+ await catalogDB.attachMedia(req.params.id, parsed.mediaKey, parsed.kind, {
+ role: null, caption,
+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),
+ });
+ const age = body.variant?.age ?? (body.inferAge ? inferAgeFromText(caption) : undefined);
+ const variant = { ...(body.variant || {}), ...(age !== undefined ? { age } : {}) };
+ const patch = { ...(Object.keys(variant).length ? { variant } : {}), ...(body.tags ? { tags: body.tags } : {}) };
+ attached.push(Object.keys(patch).length ? await catalogDB.updateMediaLibrary(req.params.id, parsed.mediaKey, parsed.kind, patch) : { mediaKey: parsed.mediaKey, kind: parsed.kind });
+ }
+ res.status(201).json({ attached, skipped });
}));
// Integrity surface: media keys on this ingredient that don't resolve against
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 79e1c8bc1e..7d11824b80 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -698,6 +698,7 @@ CREATE TABLE IF NOT EXISTS catalog_ingredient_media (
role VARCHAR(64), -- optional free label (e.g. 'hero-shot', 'angry')
caption TEXT,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb, -- bounded generation provenance when present
+ library JSONB NOT NULL DEFAULT '{}'::jsonb, -- Casting reference library: variant/tags/guide
created_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE, -- soft-delete tombstone so detaches propagate to peers
deleted_at TIMESTAMPTZ,
@@ -877,7 +878,8 @@ BEGIN
OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at
OR NEW.role IS DISTINCT FROM OLD.role
OR NEW.caption IS DISTINCT FROM OLD.caption
- OR NEW.metadata IS DISTINCT FROM OLD.metadata THEN
+ OR NEW.metadata IS DISTINCT FROM OLD.metadata
+ OR NEW.library IS DISTINCT FROM OLD.library THEN
IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN
NEW.updated_at := catalog_next_change_clock(OLD.updated_at);
END IF;
diff --git a/server/services/catalogDB/media.js b/server/services/catalogDB/media.js
index c3f743dcaa..35220220b3 100644
--- a/server/services/catalogDB/media.js
+++ b/server/services/catalogDB/media.js
@@ -11,6 +11,7 @@
import { query, withTransaction } from '../../lib/db.js';
import { resolveImageInputPath } from '../../lib/fileUtils.js';
import { rowToMedia } from './shared.js';
+import { MAX_CAST_GUIDES, normalizeLibrary } from '../../lib/catalogMediaLibrary.js';
import { assertCatalogIdentityWritable, assertCatalogAssociationRemovable } from './identityAccess.js';
const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value || {}, key);
@@ -133,3 +134,50 @@ export async function getMissingMediaForIngredient(ingredientId) {
.filter((m) => RESOLVABLE_MEDIA_KINDS.has(m.kind) && !resolveImageInputPath(m.mediaKey))
.map((m) => ({ mediaKey: m.mediaKey, kind: m.kind }));
}
+
+// Casting reference library: merge a variant/tags/guide patch into one live
+// media row. Turning a guide ON is serialized on the owning ingredient row and
+// refused (409) past MAX_CAST_GUIDES so the render picker's cap holds.
+export async function updateMediaLibrary(ingredientId, mediaKey, kind, patch = {}) {
+ ingredientId = await assertCatalogIdentityWritable(ingredientId);
+ return withTransaction(async (client) => {
+ await client.query('SELECT id FROM catalog_ingredients WHERE id = catalog_resolve_ingredient_id($1) FOR UPDATE', [ingredientId]);
+ const cur = await client.query(
+ `SELECT * FROM catalog_ingredient_media
+ WHERE ingredient_id = catalog_resolve_ingredient_id($1) AND media_key = $2 AND kind = $3 AND deleted = false`,
+ [ingredientId, mediaKey, kind],
+ );
+ const row = cur.rows[0];
+ if (!row) {
+ const err = new Error('Media not attached to this ingredient');
+ err.status = 404;
+ throw err;
+ }
+ const prev = normalizeLibrary(row.library);
+ const next = normalizeLibrary({
+ ...prev,
+ ...(hasOwn(patch, 'variant') ? { variant: patch.variant } : {}),
+ ...(hasOwn(patch, 'tags') ? { tags: patch.tags } : {}),
+ ...(hasOwn(patch, 'guide') ? { guide: patch.guide } : {}),
+ });
+ if (next.guide === true && prev.guide !== true) {
+ const count = await client.query(
+ `SELECT COUNT(*)::int AS n FROM catalog_ingredient_media
+ WHERE ingredient_id = catalog_resolve_ingredient_id($1) AND deleted = false AND library->>'guide' = 'true'`,
+ [ingredientId],
+ );
+ if (count.rows[0].n >= MAX_CAST_GUIDES) {
+ const err = new Error(`At most ${MAX_CAST_GUIDES} references can be render guides`);
+ err.status = 409;
+ throw err;
+ }
+ }
+ const result = await client.query(
+ `UPDATE catalog_ingredient_media SET library = $4::jsonb
+ WHERE ingredient_id = catalog_resolve_ingredient_id($1) AND media_key = $2 AND kind = $3 AND deleted = false
+ RETURNING *`,
+ [ingredientId, mediaKey, kind, JSON.stringify(next)],
+ );
+ return rowToMedia(result.rows[0]);
+ });
+}
diff --git a/server/services/catalogDB/merge.js b/server/services/catalogDB/merge.js
index ced7cbb3f0..a06b22076c 100644
--- a/server/services/catalogDB/merge.js
+++ b/server/services/catalogDB/merge.js
@@ -155,10 +155,10 @@ export async function mergeIngredients(input) {
caption: `Preserved from ${row.name}`, metadata: {}, created_at: row.created_at });
}
for (const row of mediaCopies.values()) {
- await client.query(`INSERT INTO catalog_ingredient_media (ingredient_id, media_key, kind, role, caption, metadata, created_at)
- VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)
+ await client.query(`INSERT INTO catalog_ingredient_media (ingredient_id, media_key, kind, role, caption, metadata, created_at, library)
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8::jsonb)
ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE SET deleted = false, deleted_at = NULL`,
- [survivorId, row.media_key, row.kind, row.role, row.caption, JSON.stringify(row.metadata), row.created_at]);
+ [survivorId, row.media_key, row.kind, row.role, row.caption, JSON.stringify(row.metadata), row.created_at, JSON.stringify(row.library || {})]);
}
await client.query(`INSERT INTO catalog_ingredient_relations (from_id, to_id, kind, created_at)
SELECT CASE WHEN from_id = $1 THEN $2 ELSE from_id END,
diff --git a/server/services/catalogDB/shared.js b/server/services/catalogDB/shared.js
index 4f1f3b3b78..365951bb0f 100644
--- a/server/services/catalogDB/shared.js
+++ b/server/services/catalogDB/shared.js
@@ -171,6 +171,7 @@ export function rowToMedia(row) {
role: row.role ?? null,
caption: row.caption ?? null,
metadata: row.metadata && typeof row.metadata === 'object' && !Array.isArray(row.metadata) ? row.metadata : {},
+ library: row.library && typeof row.library === 'object' && !Array.isArray(row.library) ? row.library : {},
createdAt: row.created_at.toISOString(),
deleted: !!row.deleted,
deletedAt: row.deleted_at?.toISOString() ?? null,
diff --git a/server/services/catalogDB/sync.js b/server/services/catalogDB/sync.js
index 7cb7470ef6..5f8df52edb 100644
--- a/server/services/catalogDB/sync.js
+++ b/server/services/catalogDB/sync.js
@@ -17,6 +17,7 @@
* peer's own clock. See `upsertRefFromPeer` for the full rationale.
*/
+import { normalizeLibrary } from '../../lib/catalogMediaLibrary.js';
import { query, withTransaction, arrayToPgvector } from '../../lib/db.js';
import {
rowToScrap,
@@ -122,6 +123,13 @@ export async function upsertMediaFromPeer(media) {
const metadataPlaceholder = hasMetadata ? `, $${hasTombstoneFields ? 10 : 7}` : '';
const metadataUpdate = hasMetadata ? ', metadata = EXCLUDED.metadata' : '';
const metadataParam = hasMetadata ? [JSON.stringify(media.metadata || {})] : [];
+ // Casting reference library (catalog v12): absent = no opinion, same as metadata.
+ const hasLibrary = Object.prototype.hasOwnProperty.call(media, 'library')
+ && media.library && typeof media.library === 'object' && !Array.isArray(media.library);
+ const libraryColumn = hasLibrary ? ', library' : '';
+ const libraryPlaceholder = hasLibrary ? `, ${(hasTombstoneFields ? 10 : 7) + (hasMetadata ? 1 : 0)}` : '';
+ const libraryUpdate = hasLibrary ? ', library = EXCLUDED.library' : '';
+ const libraryParam = hasLibrary ? [JSON.stringify(normalizeLibrary(media.library))] : [];
if (hasTombstoneFields) {
// #8347 revival guard — see upsertRelationFromPeer for the rationale.
// `updated_at` also moves on a role/caption/metadata-only edit (the
@@ -130,30 +138,30 @@ export async function upsertMediaFromPeer(media) {
const updatedAtClock = media.updatedAt || media.deletedAt || media.createdAt;
await query(
`INSERT INTO catalog_ingredient_media
- (ingredient_id, media_key, kind, role, caption, created_at, deleted, deleted_at, updated_at${metadataColumn})
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9${metadataPlaceholder})
+ (ingredient_id, media_key, kind, role, caption, created_at, deleted, deleted_at, updated_at${metadataColumn}${libraryColumn})
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9${metadataPlaceholder}${libraryPlaceholder})
ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE
SET role = EXCLUDED.role,
caption = EXCLUDED.caption,
deleted = EXCLUDED.deleted,
deleted_at = EXCLUDED.deleted_at,
- updated_at = EXCLUDED.updated_at${metadataUpdate}
+ updated_at = EXCLUDED.updated_at${metadataUpdate}${libraryUpdate}
WHERE EXCLUDED.updated_at > catalog_ingredient_media.updated_at`,
[
media.ingredientId, media.mediaKey, media.kind,
media.role ?? null, media.caption ?? null, media.createdAt,
!!media.deleted, media.deletedAt || null, updatedAtClock,
- ...metadataParam,
+ ...metadataParam, ...libraryParam,
],
);
} else {
await query(
`INSERT INTO catalog_ingredient_media
- (ingredient_id, media_key, kind, role, caption, created_at${metadataColumn})
- VALUES ($1, $2, $3, $4, $5, $6${metadataPlaceholder})
+ (ingredient_id, media_key, kind, role, caption, created_at${metadataColumn}${libraryColumn})
+ VALUES ($1, $2, $3, $4, $5, $6${metadataPlaceholder}${libraryPlaceholder})
ON CONFLICT (ingredient_id, media_key, kind) DO UPDATE
- SET role = EXCLUDED.role, caption = EXCLUDED.caption${metadataUpdate}`,
- [media.ingredientId, media.mediaKey, media.kind, media.role ?? null, media.caption ?? null, media.createdAt, ...metadataParam],
+ SET role = EXCLUDED.role, caption = EXCLUDED.caption${metadataUpdate}${libraryUpdate}`,
+ [media.ingredientId, media.mediaKey, media.kind, media.role ?? null, media.caption ?? null, media.createdAt, ...metadataParam, ...libraryParam],
);
}
});