Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: catalog universe/series/tag filters, pagination, and Albums view (#1762)
[._.]/ Adam Eivyf779d84375d4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2eff48068d..b931e00c73 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased+## Catalog++- **[issue-1762] Catalog gains universe/series/tag filters, real pagination, and an Albums grouped view.** The Catalog page had outgrown a flat, hard-capped list of 200 ingredients with only type chips + search. It now exposes the universe, series, and tag facets the server already understood as filter dropdowns (series scoped to the chosen universe), all reflected in the URL (`?type=&universe=&series=&tag=&q=&view=`) so a filtered catalog is shareable and back-button-safe. The flat Grid view paginates past the old cap with a "Load more" button (60/page) and an honest "showing X of N" line. A new **Albums** view groups ingredients by universe with a pinned **"Unsorted / Raw"** album (ingredients linked to nothing yet) and an **"Orphaned"** album (refs whose universe/series was deleted) — each lazy-loading its cards on first expand. The multi-select action bar can now **place a selection into a universe/series** directly, closing the raw → placed loop. Server-side: `listIngredients` gained `refKind`/`refId`/`unlinked`/`orphaned` filters, a new `GET /api/catalog/facets` aggregates type/universe/series/tag facets plus unlinked/orphaned bucket counts in one round-trip, and the shared `<CatalogCard>` is extracted so the grid and albums render identical cards. (`server/services/catalogDB.js`, `server/routes/catalog.js`, `server/lib/catalogValidation.js`, `client/src/pages/Catalog.jsx`, `client/src/components/catalog/`, `client/src/services/apiCatalog.js`)+## Music Video production mode- **[issue-1760] Groundwork: offline beat/tempo/section analysis of an audio track (Phase 0 spike).** The first slice of the planned Music Video production mode proves the riskiest unknown — that a music track's BPM, beat grid, 4/4 downbeats, and a coarse section map can be extracted **fully offline with no new dependency**, using only ffmpeg (already required) plus a pure-JS DSP core (onset-strength envelope → tempo-weighted autocorrelation → beat-phase fit → energy-novelty sections). No Python, no ML model download, no network — so it runs the same in CI and on every install. There's no user-facing surface yet; this is the analyzer the upcoming director scene board and beat-snapped render build on. (`server/services/musicVideo/audioAnalysis.js`)diff --git a/client/src/components/CatalogCastPanel.jsx b/client/src/components/CatalogCastPanel.jsxindex 8de11be77e..5576462508 100644--- a/client/src/components/CatalogCastPanel.jsx+++ b/client/src/components/CatalogCastPanel.jsx@@ -22,18 +22,7 @@ import {linkCatalogIngredient,unlinkCatalogIngredient,} from '../services/apiCatalog';-import { CATALOG_BADGE_BY_ID } from '../lib/catalogTypes';--const ROLE_BY_TYPE = {- character: 'cast-character',- place: 'cast-place',- object: 'cast-object',- idea: 'reference',- scene: 'reference',- concept: 'reference',-};--const roleForType = (type) => ROLE_BY_TYPE[type] || 'reference';+import { CATALOG_BADGE_BY_ID, catalogRefRoleForType as roleForType } from '../lib/catalogTypes';function snippet(payload) {if (!payload || typeof payload !== 'object') return '';diff --git a/client/src/components/catalog/CatalogAlbum.jsx b/client/src/components/catalog/CatalogAlbum.jsxnew file mode 100644index 0000000000..ab6f8aa4ad--- /dev/null+++ b/client/src/components/catalog/CatalogAlbum.jsx@@ -0,0 +1,118 @@+/**+ * CatalogAlbum — a collapsible group section in the Catalog "Albums" view (#1762).+ *+ * One album per live universe, plus the pinned "Unsorted / Raw" and "Orphaned"+ * albums. Cards lazy-load via `loadItems()` the FIRST time the album is+ * expanded (album headers show the count from /facets up front, so an unexpanded+ * album costs nothing). Reuses <CatalogCard> so album cards match the flat grid.+ */++import { useState, useEffect, useCallback } from 'react';+import { ChevronRight, ChevronDown, Loader2 } from 'lucide-react';+import CatalogCard from './CatalogCard';++export default function CatalogAlbum({+ title,+ subtitle,+ count,+ defaultExpanded = false,+ loadItems,+ getType,+ selectedIds,+ onToggleSelect,+ armedId,+ onArm,+ onCancelArm,+ onConfirmDelete,+}) {+ const [expanded, setExpanded] = useState(defaultExpanded);+ // `null` = not yet loaded (distinct from `[]` = loaded-and-empty), so an+ // empty album doesn't re-fetch on every expand toggle.+ const [items, setItems] = useState(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState('');++ const ensureLoaded = useCallback(async () => {+ if (items !== null || loading) return;+ setLoading(true);+ setError('');+ const list = await loadItems().catch((err) => {+ setError(err?.message || 'Failed to load album');+ return null;+ });+ setLoading(false);+ if (Array.isArray(list)) setItems(list);+ }, [items, loading, loadItems]);++ // Load the first time the album is expanded — covers both an explicit toggle+ // and a `defaultExpanded` album that mounts already open (the pinned Raw album).+ useEffect(() => {+ if (expanded) ensureLoaded();+ }, [expanded, ensureLoaded]);++ const toggle = () => setExpanded((e) => !e);++ // Album-local optimistic delete: remove the card immediately, restore it if+ // the parent's delete handler reports failure (it owns the toast + rollback+ // of shared state like selection + facet counts).+ const handleDelete = async (it) => {+ const idx = (items || []).findIndex((x) => x.id === it.id);+ setItems((prev) => (prev || []).filter((x) => x.id !== it.id));+ const ok = await onConfirmDelete(it);+ if (!ok) {+ setItems((prev) => {+ if ((prev || []).some((x) => x.id === it.id)) return prev;+ const next = [...(prev || [])];+ next.splice(Math.max(0, idx), 0, it);+ return next;+ });+ }+ };++ return (+ <section className="border border-port-border rounded-lg overflow-hidden bg-port-card/40">+ <button+ type="button"+ onClick={toggle}+ aria-expanded={expanded}+ className="w-full flex items-center gap-2 px-4 py-3 text-left hover:bg-port-bg/40"+ >+ {expanded ? <ChevronDown size={16} className="text-gray-400" /> : <ChevronRight size={16} className="text-gray-400" />}+ <span className="text-white font-medium">{title}</span>+ {subtitle ? <span className="text-xs text-gray-500">{subtitle}</span> : null}+ <span className="ml-auto text-xs text-gray-400 px-2 py-0.5 rounded-full border border-port-border">+ {count}+ </span>+ </button>+ {expanded && (+ <div className="px-4 pb-4">+ {loading ? (+ <div className="flex items-center gap-2 text-sm text-gray-500 py-3">+ <Loader2 size={14} className="animate-spin" /> Loading…+ </div>+ ) : error ? (+ <div className="text-sm text-port-error py-3">{error}</div>+ ) : (items && items.length > 0) ? (+ <ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">+ {items.map((it) => (+ <CatalogCard+ key={it.id}+ ingredient={it}+ getType={getType}+ selected={selectedIds.has(it.id)}+ onToggleSelect={onToggleSelect}+ armed={armedId === it.id}+ onArm={onArm}+ onCancelArm={onCancelArm}+ onConfirmDelete={handleDelete}+ />+ ))}+ </ul>+ ) : (+ <div className="text-sm text-gray-500 py-3">No ingredients in this album.</div>+ )}+ </div>+ )}+ </section>+ );+}diff --git a/client/src/components/catalog/CatalogCard.jsx b/client/src/components/catalog/CatalogCard.jsxnew file mode 100644index 0000000000..feefb12604--- /dev/null+++ b/client/src/components/catalog/CatalogCard.jsx@@ -0,0 +1,134 @@+/**+ * CatalogCard — a single Creative Ingredient card.+ *+ * Extracted from Catalog.jsx (#1762) so the flat grid AND the albums grouped+ * view render identical cards. The card is one big <Link> (clicking anywhere+ * opens the editor); the selection checkbox and the armed two-click delete+ * control are absolute-positioned siblings of the Link so their clicks never+ * bubble to the anchor.+ */++import { Link } from 'react-router-dom';+import { Sparkles, Trash2 } from 'lucide-react';+import MediaImage from '../MediaImage';+import { payloadSnippet } from '../../lib/catalogTypes';++function TypeBadge({ type, getType }) {+ const meta = getType(type);+ if (!meta) return null;+ return (+ <span className={`inline-block text-[10px] uppercase tracking-wider px-2 py-0.5 rounded border ${meta.badgeColor}`}>+ {meta.label}+ </span>+ );+}++// Card thumbnail: the ingredient's portrait (or most recent reference image),+// resolved from the media library at /data/images/<key>. With no image we show a+// dimmed Sparkles placeholder; with one we render through <MediaImage>, which+// tolerates a not-yet-arrived peer asset (shows "Syncing" and auto-swaps to the+// live image on the asset-arrived event) instead of permanently breaking on a+// transient 404. Either way the slot keeps a fixed footprint so the grid aligns.+function CardThumb({ mediaKey, alt }) {+ return (+ <div className="w-14 h-14 shrink-0 rounded-md overflow-hidden border border-port-border bg-port-bg flex items-center justify-center">+ {mediaKey ? (+ <MediaImage+ src={`/data/images/${mediaKey}`}+ alt={alt}+ className="w-full h-full object-cover"+ loading="lazy"+ />+ ) : (+ <Sparkles size={18} className="text-gray-600" aria-hidden="true" />+ )}+ </div>+ );+}++export default function CatalogCard({+ ingredient: it,+ getType,+ selected,+ onToggleSelect,+ armed,+ onArm,+ onCancelArm,+ onConfirmDelete,+}) {+ const name = it.name || '(untitled)';+ const snippet = payloadSnippet(it.payload, it.type, 120, getType);+ return (+ <li+ 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={() => onToggleSelect(it)}+ 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 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">+ <span className="block text-white font-medium truncate">{name}</span>+ <span className="flex items-center gap-1.5 flex-wrap">+ <TypeBadge type={it.type} getType={getType} />+ {(it.tags || []).slice(0, 4).map((tag) => (+ <span key={tag} className="text-[10px] px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-gray-400">+ {tag}+ </span>+ ))}+ </span>+ {snippet ? (+ <span className="text-xs text-gray-400 line-clamp-2">{snippet}</span>+ ) : null}+ </span>+ </Link>+ <div className="absolute top-2 right-2">+ {/* The delete control is a sibling of the <Link>, not a descendant, so a+ click on these buttons never traverses the anchor. */}+ {armed ? (+ <span className="inline-flex items-center gap-1 text-xs bg-port-card border border-port-border rounded px-1 py-0.5 shadow-sm">+ <span className="text-gray-400 pl-1">Delete?</span>+ <button+ type="button"+ onClick={() => onConfirmDelete(it)}+ className="px-2 py-0.5 rounded bg-port-error/20 text-port-error hover:bg-port-error/30 font-medium"+ >+ Yes+ </button>+ <button+ type="button"+ onClick={onCancelArm}+ className="px-2 py-0.5 rounded text-gray-400 hover:text-white"+ >+ No+ </button>+ </span>+ ) : (+ <button+ type="button"+ onClick={() => onArm(it.id)}+ className="p-1.5 rounded text-gray-500 hover:text-port-error bg-port-card"+ aria-label={`Delete ${name}`}+ title="Delete ingredient"+ >+ <Trash2 size={14} />+ </button>+ )}+ </div>+ </li>+ );+}diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.jsindex b6dedd5fd8..5fac0aac20 100644--- a/client/src/lib/catalogTypes.js+++ b/client/src/lib/catalogTypes.js@@ -320,6 +320,19 @@ export const CATALOG_BADGE_BY_ID = Object.freeze(Object.fromEntries(CATALOG_TYPES.map((t) => [t.id, t.badgeColor])),);+// Catalog ingredient `type` → ref role when linking the ingredient to a+// universe/series from the UI (#1762 bulk "Add to universe/series" + the cast+// panel). character/place/object carry a typed `cast-*` role; everything else+// (idea/scene/concept/user types) links as a generic 'reference'. The server+// validates role as a free string (min1/max64), so this is the client-side+// convention shared by CatalogCastPanel and the Catalog bulk-place action.+const CATALOG_REF_ROLE_BY_TYPE = Object.freeze({+ character: 'cast-character',+ place: 'cast-place',+ object: 'cast-object',+});+export const catalogRefRoleForType = (type) => CATALOG_REF_ROLE_BY_TYPE[type] || 'reference';+/*** Pull a short snippet from a payload using a type's fallback chain (first* non-empty key wins), trimmed + ellipsised to `max` chars. When `typeId` isdiff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsxindex 2bc1588047..45a4e7d86d 100644--- a/client/src/pages/Catalog.jsx+++ b/client/src/pages/Catalog.jsx@@ -2,25 +2,34 @@* Catalog page — index of Creative Ingredients.** Lists every ingredient (character/place/object/idea/scene/concept) the user- * has captured into the catalog. Type chips along the top filter by kind and- * show the per-type count from `/api/catalog/stats`. The "+ New" inline form- * mirrors the Pipeline series-create pattern; "Ingest" links to the paste-and-- * extract page. Delete uses an armed two-click confirm (no window.confirm).+ * has captured into the catalog. Type chips + Universe/Series/Tag dropdowns+ * filter the set (#1762); all filter state lives in the URL (`?type=&universe=+ * &series=&tag=&q=&view=`) so a filtered catalog is shareable + back-button-+ * safe. The flat Grid view paginates past the old 200-item cap with "Load more";+ * the Albums view groups ingredients by universe with pinned "Unsorted / Raw"+ * and "Orphaned" albums. The "+ New" inline form mirrors the Pipeline+ * series-create pattern; "Ingest" links to the paste-and-extract page. Delete+ * uses an armed two-click confirm (no window.confirm); the multi-select action+ * bar can Remix the selection into Story Builder or place it into a+ * universe/series.*/-import { useState, useEffect, useCallback } from 'react';-import { Link, useNavigate } from 'react-router-dom';-import { Sparkles, Plus, Search, FileInput, Trash2, Loader2, RefreshCw, Wand2, X } from 'lucide-react';+import { useState, useEffect, useCallback, useMemo } from 'react';+import { Link, useNavigate, useSearchParams } from 'react-router-dom';+import { Sparkles, Plus, Search, FileInput, Loader2, RefreshCw, Wand2, X, LayoutGrid, Library, FolderPlus } from 'lucide-react';import toast from '../components/ui/Toast';import {listCatalogIngredients,createCatalogIngredient,deleteCatalogIngredient,+ linkCatalogIngredient,getCatalogStats,+ getCatalogFacets,rerunCatalogMigration,} from '../services/apiCatalog';-import MediaImage from '../components/MediaImage';-import { payloadSnippet } from '../lib/catalogTypes';+import CatalogCard from '../components/catalog/CatalogCard';+import CatalogAlbum from '../components/catalog/CatalogAlbum';+import { catalogRefRoleForType } from '../lib/catalogTypes';import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';// All type-derived UI (chips, badge color, inline-form primary content@@ -28,38 +37,10 @@ import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';// user-defined). The static built-ins are the synchronous fallback inside the// hook, so adding a type — built-in or user — surfaces here automatically.-function TypeBadge({ type, getType }) {- const meta = getType(type);- if (!meta) return null;- return (- <span className={`inline-block text-[10px] uppercase tracking-wider px-2 py-0.5 rounded border ${meta.badgeColor}`}>- {meta.label}- </span>- );-}--// Card thumbnail: the ingredient's portrait (or most recent reference image),-// resolved from the media library at /data/images/<key>. With no image we show a-// dimmed Sparkles placeholder; with one we render through <MediaImage>, which-// tolerates a not-yet-arrived peer asset (shows "Syncing" and auto-swaps to the-// live image on the asset-arrived event) instead of permanently breaking on a-// transient 404. Either way the slot keeps a fixed footprint so the grid aligns.-function CardThumb({ mediaKey, alt }) {- return (- <div className="w-14 h-14 shrink-0 rounded-md overflow-hidden border border-port-border bg-port-bg flex items-center justify-center">- {mediaKey ? (- <MediaImage- src={`/data/images/${mediaKey}`}- alt={alt}- className="w-full h-full object-cover"- loading="lazy"- />- ) : (- <Sparkles size={18} className="text-gray-600" aria-hidden="true" />- )}- </div>- );-}+// Page size for the flat grid's "Load more" pagination. 60 keeps the first+// paint light while still filling a 3-column grid several rows deep; the old+// fixed `limit: 200` silently truncated installs with more ingredients.+const PAGE_SIZE = 60;// 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@@ -75,37 +56,77 @@ export default function Catalog() {// 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();++ // ── URL-synced filter state (linkable routes per CLAUDE.md) ────────────────+ const [searchParams, setSearchParams] = useSearchParams();+ const selectedType = searchParams.get('type') || '';+ const selectedUniverse = searchParams.get('universe') || '';+ const selectedSeries = searchParams.get('series') || '';+ const selectedTag = searchParams.get('tag') || '';+ const view = searchParams.get('view') === 'albums' ? 'albums' : 'grid';++ // Merge a patch into the URL search params, dropping keys set to '' so a+ // cleared filter leaves the URL clean. `replace` avoids history spam while+ // typing; discrete clicks push so Back returns to the prior filter.+ const updateParams = useCallback((patch, { replace = false } = {}) => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ for (const [k, v] of Object.entries(patch)) {+ if (v == null || v === '') next.delete(k);+ else next.set(k, v);+ }+ return next;+ }, { replace });+ }, [setSearchParams]);++ // Two-stage search: `searchInput` is what the user is typing; `q` is the+ // debounced value that drives the list fetch (and is mirrored to the URL).+ // Seeded from the URL once so a shared/reloaded `?q=` link restores the box.+ const [searchInput, setSearchInput] = useState(() => searchParams.get('q') || '');+ const [q, setQ] = useState(() => searchParams.get('q') || '');++ const [stats, setStats] = useState(null);+ const [facets, setFacets] = useState(null);++ // Grid pagination state.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 [hasMore, setHasMore] = useState(false);+ const [loading, setLoading] = useState(true);+ const [loadingMore, setLoadingMore] = useState(false);++ // Bump after a mutation (delete/add-to-ref/create/sync) to force the lazy+ // albums to remount and re-fetch their membership. The grid mutates its own+ // state optimistically, so it is NOT keyed on this.+ const [dataVersion, setDataVersion] = useState(0);++ // Multi-select. `selectedIds` is the membership Set (drives the action-bar+ // count + card highlight); `selectedItems` keeps the full ingredient objects+ // so the "Add to universe/series" action can derive each one's ref role+ // without a re-fetch (selection can span grid + albums).const [selectedIds, setSelectedIds] = useState(() => new Set());+ const [selectedItems, setSelectedItems] = useState(() => new Map());const [remixMenuOpen, setRemixMenuOpen] = useState(false);- const [stats, setStats] = useState(null);- const [loading, setLoading] = useState(true);- const [selectedType, setSelectedType] = useState('');- // Two-stage search: `searchInput` is what the user is typing; `q` is the- // debounced value that actually drives the list fetch. 300ms gap.- const [searchInput, setSearchInput] = useState('');- const [q, setQ] = useState('');- // Inline create form. `content` is a single freeform textarea that lands in- // the per-type primary content field on submit (physicalDescription for- // character, description for place/object, summary for idea/scene/concept)- // so users don't have to navigate to the editor just to capture the body.+ const [addMenuOpen, setAddMenuOpen] = useState(false);++ // Inline create form.const [showForm, setShowForm] = useState(false);const [form, setForm] = useState({ type: 'character', name: '', content: '' });const [creating, setCreating] = useState(false);// Armed-row id for two-click delete (no window.confirm).const [armedId, setArmedId] = useState(null);- // "Sync from Universes" — re-runs the bible→catalog backfill so canon- // characters/places/objects added after the one-time boot promotion show up- // in the catalog. In flight while the server walks every universe.+ // "Sync from Universes" — re-runs the bible→catalog backfill.const [syncing, setSyncing] = useState(false);+ // Debounce typing → q, and mirror q to the URL (replace, to avoid history+ // spam). The fetch keys on the local `q`; the URL copy is for shareability.useEffect(() => {- const t = setTimeout(() => setQ(searchInput.trim()), 300);+ const t = setTimeout(() => {+ const trimmed = searchInput.trim();+ setQ(trimmed);+ updateParams({ q: trimmed }, { replace: true });+ }, 300);return () => clearTimeout(t);- }, [searchInput]);+ }, [searchInput, updateParams]);const loadStats = useCallback(() => {getCatalogStats({ silent: true })@@ -113,18 +134,36 @@ export default function Catalog() {.catch(() => {});}, []);- const loadItems = useCallback(() => {+ const loadFacets = useCallback(() => {+ getCatalogFacets({ silent: true })+ .then((f) => setFacets(f || null))+ .catch(() => {});+ }, []);++ // Build the list-query params from the active filters. The server accepts a+ // single ref filter, so series (more specific) wins over universe; type/tag/q+ // compose with it.+ const buildListParams = useCallback(() => {+ const p = {};+ if (selectedType) p.type = selectedType;+ if (selectedTag) p.tag = selectedTag;+ if (q) p.q = q;+ if (selectedSeries) { p.refKind = 'series'; p.refId = selectedSeries; }+ else if (selectedUniverse) { p.refKind = 'universe'; p.refId = selectedUniverse; }+ return p;+ }, [selectedType, selectedTag, q, selectedSeries, selectedUniverse]);++ // Fetch page 1 for the grid, replacing the list. Used by the filter-change+ // effect and by the post-sync reload.+ const loadFirstPage = useCallback(() => {let cancelled = false;setLoading(true);- listCatalogIngredients({- type: selectedType || undefined,- q: q || undefined,- limit: 200,- silent: true,- })+ listCatalogIngredients({ ...buildListParams(), limit: PAGE_SIZE, offset: 0, silent: true }).then((data) => {if (cancelled) return;- setItems(Array.isArray(data?.items) ? data.items : []);+ const list = Array.isArray(data?.items) ? data.items : [];+ setItems(list);+ setHasMore(list.length === PAGE_SIZE);setLoading(false);}).catch((err) => {@@ -133,14 +172,73 @@ export default function Catalog() {setLoading(false);});return () => { cancelled = true; };- }, [selectedType, q]);+ }, [buildListParams]);++ // Grid view: (re)load page 1 whenever the filters change. Albums manage their+ // own lazy loads, so skip the grid fetch entirely in that view.+ useEffect(() => {+ if (view !== 'grid') return undefined;+ return loadFirstPage();+ }, [view, loadFirstPage]);- useEffect(() => loadItems(), [loadItems]);useEffect(() => loadStats(), [loadStats]);+ useEffect(() => loadFacets(), [loadFacets]);++ const loadMore = () => {+ setLoadingMore(true);+ listCatalogIngredients({ ...buildListParams(), limit: PAGE_SIZE, offset: items.length, silent: true })+ .then((data) => {+ const list = Array.isArray(data?.items) ? data.items : [];+ setItems((prev) => [...prev, ...list]);+ setHasMore(list.length === PAGE_SIZE);+ setLoadingMore(false);+ })+ .catch((err) => {+ toast.error(err?.message || 'Failed to load more');+ setLoadingMore(false);+ });+ };const totalCount = stats?.total ?? items.length;const countForType = (id) => stats?.byType?.[id] || 0;+ // The honest "of N" for the grid count line. We can answer it cheaply from+ // /facets only for the single-filter cases; for combined filters or a search+ // query we don't know the total without a count round-trip, so we show just+ // "Showing X" (with a trailing + when more pages remain).+ const knownTotal = useMemo(() => {+ if (!facets) return null;+ const active = [+ selectedType && 'type', selectedUniverse && 'universe',+ selectedSeries && 'series', selectedTag && 'tag', q && 'q',+ ].filter(Boolean);+ if (active.length === 0) return facets.total;+ if (active.length > 1) return null;+ const only = active[0];+ if (only === 'type') return facets.types.find((t) => t.type === selectedType)?.count ?? null;+ if (only === 'series') return facets.series.find((s) => s.refId === selectedSeries)?.count ?? null;+ if (only === 'universe') return facets.universes.find((u) => u.refId === selectedUniverse)?.count ?? null;+ if (only === 'tag') return facets.tags.find((t) => t.tag === selectedTag)?.count ?? null;+ return null;+ }, [facets, selectedType, selectedUniverse, selectedSeries, selectedTag, q]);++ // Series options scoped to the chosen universe (decision #1: the series+ // dropdown narrows within the selected universe). With no universe chosen,+ // show all series and rely on the universe sublabel for disambiguation.+ const seriesOptions = useMemo(() => {+ const all = facets?.series || [];+ if (!selectedUniverse) return all;+ return all.filter((s) => s.universeId === selectedUniverse);+ }, [facets, selectedUniverse]);++ const hasActiveFilters = !!(selectedType || selectedUniverse || selectedSeries || selectedTag || q);++ const clearFilters = () => {+ setSearchInput('');+ setQ('');+ updateParams({ type: '', universe: '', series: '', tag: '', q: '' });+ };+const handleCreate = async (e) => {e.preventDefault();const name = form.name.trim();@@ -166,56 +264,89 @@ export default function Catalog() {closeForm();// Only prepend optimistically if the new row would actually pass the// current filter — otherwise it appears in a filtered view it doesn't- // match and lingers until the next refetch. Search-text gating is best-- // effort (string includes vs server-side full-text); when in doubt, skip- // the optimistic insert so the user just sees a clean view + accurate stats.+ // match and lingers until the next refetch. A freshly-created ingredient is+ // unlinked, so it never belongs in a universe/series-filtered grid.const matchesType = !selectedType || created.type === selectedType;- const matchesSearch = !q- || (created.name || '').toLowerCase().includes(q.toLowerCase());- if (matchesType && matchesSearch) {+ const matchesSearch = !q || (created.name || '').toLowerCase().includes(q.toLowerCase());+ const refFiltered = !!(selectedUniverse || selectedSeries);+ if (view === 'grid' && matchesType && matchesSearch && !refFiltered) {setItems((prev) => [created, ...prev]);}loadStats();+ loadFacets();+ setDataVersion((v) => v + 1);};- 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. Remember whether it WAS selected so a failed- // delete can restore it (otherwise a still-live ingredient silently vanishes- // from the selection and a later Remix omits it).+ // Drop an id from both selection structures (used on delete + after a bulk+ // place + on explicit clear).+ const dropSelection = (id) => {+ setSelectedIds((prev) => {+ if (!prev.has(id)) return prev;+ const next = new Set(prev);+ next.delete(id);+ return next;+ });+ setSelectedItems((prev) => {+ if (!prev.has(id)) return prev;+ const next = new Map(prev);+ next.delete(id);+ return next;+ });+ };++ // The API + side-effect half of a delete, shared by the grid and the albums.+ // Returns whether the delete succeeded so the caller can roll its own+ // optimistic list mutation back. Selection cleanup + stats/facets refresh and+ // the error toast live here so both call sites stay in sync.+ const deleteIngredientApi = async (it) => {const wasSelected = selectedIds.has(it.id);- if (wasSelected) {- setSelectedIds((prev) => {- if (!prev.has(it.id)) return prev;- const next = new Set(prev);- next.delete(it.id);- return next;+ const wasItem = selectedItems.get(it.id);+ if (wasSelected) dropSelection(it.id);+ const ok = await deleteCatalogIngredient(it.id, { silent: true })+ .then(() => true)+ .catch((err) => {+ toast.error(err?.message || 'Delete failed');+ // The ingredient still exists — restore it to the selection.+ if (wasSelected) {+ setSelectedIds((prev) => (prev.has(it.id) ? prev : new Set(prev).add(it.id)));+ if (wasItem) setSelectedItems((prev) => (prev.has(it.id) ? prev : new Map(prev).set(it.id, wasItem)));+ }+ return false;});+ if (ok) {+ loadStats();+ loadFacets();+ setDataVersion((v) => v + 1);}- // Capture the original index so a failed delete restores in place rather- // than jumping the row to the top of the list.+ return ok;+ };++ // Grid delete: optimistic removal from the visible list, restored in place if+ // the API call fails.+ const confirmDelete = async (it) => {+ setArmedId(null);const originalIdx = items.findIndex((x) => x.id === it.id);setItems((prev) => prev.filter((x) => x.id !== it.id));- await deleteCatalogIngredient(it.id, { silent: true }).catch((err) => {- toast.error(err?.message || 'Delete failed');+ const ok = await deleteIngredientApi(it);+ if (!ok) {setItems((prev) => {if (prev.some((x) => x.id === it.id)) return prev;const next = [...prev];next.splice(Math.max(0, originalIdx), 0, it);return next;});- // Roll the selection back too — the ingredient still exists.- if (wasSelected) setSelectedIds((prev) => (prev.has(it.id) ? prev : new Set(prev).add(it.id)));- });- loadStats();+ }+ };++ // Album delete: the album owns its own optimistic list, so it just needs the+ // success boolean from the shared API helper.+ const albumDelete = async (it) => {+ setArmedId(null);+ return deleteIngredientApi(it);};- // Re-run the bible→catalog backfill to pull in canon entities that aren't in- // the catalog yet (the boot-time promotion only runs once per install, so- // characters added to a universe later never get promoted without this).- // `force: true` ignores the one-time marker. Idempotent — already-promoted- // entries are skipped server-side — so it's safe to click repeatedly.+ // Re-run the bible→catalog backfill to pull in canon entities not yet in the+ // catalog. `force: true` ignores the one-time marker; idempotent server-side.const handleSync = async () => {setSyncing(true);const result = await rerunCatalogMigration({ force: true, silent: true }).catch((err) => {@@ -224,11 +355,9 @@ export default function Catalog() {});setSyncing(false);if (!result) return;- // migrateBibleToCatalog catches per-entry failures and reports them in- // stats.errors — don't let a partial/failed walk read as "all good."- const stats = result?.stats ?? result ?? {};- const promoted = stats.promoted ?? 0;- const errors = stats.errors ?? 0;+ const syncStats = result?.stats ?? result ?? {};+ const promoted = syncStats.promoted ?? 0;+ const errors = syncStats.errors ?? 0;if (errors > 0) {toast.error(`Sync hit ${errors} error${errors === 1 ? '' : 's'}` +@@ -242,36 +371,44 @@ export default function Catalog() {);}if (promoted > 0) {- loadItems();+ if (view === 'grid') loadFirstPage();loadStats();+ loadFacets();+ setDataVersion((v) => v + 1);}};- // Single reset path used by Cancel + toolbar toggle + post-submit so all- // three "form dismissed" paths leave the same clean state — without this,- // stale name/content text reappears the next time the form opens.+ // Single reset path used by Cancel + toolbar toggle + post-submit.const closeForm = () => {setForm((f) => ({ type: f.type, name: '', content: '' }));setShowForm(false);};- // ── Multi-select "Remix into…" ────────────────────────────────────────────- const toggleSelect = (id) => {+ // ── Multi-select ──────────────────────────────────────────────────────────+ const toggleSelect = (it) => {setSelectedIds((prev) => {const next = new Set(prev);- if (next.has(id)) next.delete(id);- else next.add(id);+ if (next.has(it.id)) next.delete(it.id);+ else next.add(it.id);+ return next;+ });+ setSelectedItems((prev) => {+ const next = new Map(prev);+ if (next.has(it.id)) next.delete(it.id);+ else next.set(it.id, it);return next;});};const clearSelection = () => {setSelectedIds(new Set());+ setSelectedItems(new Map());setRemixMenuOpen(false);+ setAddMenuOpen(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.+ // Hand the selected ids off to the chosen remix 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;@@ -279,6 +416,45 @@ export default function Catalog() {navigate(target.to, { state: { remix: { ingredientIds } } });};+ // Bulk "Add to universe/series" (Phase 5): link every selected ingredient to+ // the chosen ref, deriving each one's role from its type. Closes the+ // raw → placed loop without leaving the page.+ const handleAddToRef = async (refKind, refId, label) => {+ const list = [...selectedItems.values()];+ setAddMenuOpen(false);+ if (list.length === 0) return;+ let ok = 0;+ let fail = 0;+ await Promise.all(list.map((ing) =>+ linkCatalogIngredient(ing.id, { refKind, refId, role: catalogRefRoleForType(ing.type) }, { silent: true })+ .then(() => { ok += 1; })+ .catch(() => { fail += 1; }),+ ));+ if (ok > 0) toast.success(`Added ${ok} ingredient${ok === 1 ? '' : 's'} to ${label}`);+ if (fail > 0) toast.error(`Failed to add ${fail} ingredient${fail === 1 ? '' : 's'} to ${label}`);+ clearSelection();+ loadFacets();+ setDataVersion((v) => v + 1);+ // Placed items may no longer match a universe/series/unlinked-filtered grid.+ if (view === 'grid') loadFirstPage();+ };++ const refTargets = useMemo(() => {+ const universes = (facets?.universes || []).map((u) => ({ refKind: 'universe', refId: u.refId, label: u.name }));+ const series = (facets?.series || []).map((s) => ({ refKind: 'series', refId: s.refId, label: s.name }));+ return { universes, series };+ }, [facets]);+ const hasRefTargets = refTargets.universes.length > 0 || refTargets.series.length > 0;++ const cardProps = {+ getType,+ selectedIds,+ onToggleSelect: toggleSelect,+ armedId,+ onArm: setArmedId,+ onCancelArm: () => setArmedId(null),+ };+return (<div><div className="flex items-center justify-between mb-6 flex-wrap gap-3">@@ -290,6 +466,25 @@ export default function Catalog() {</span></div><div className="flex items-center gap-2">+ {/* View toggle (Grid ↔ Albums), persisted in the URL. */}+ <div className="inline-flex rounded-lg border border-port-border overflow-hidden" role="group" aria-label="Catalog view">+ <button+ type="button"+ onClick={() => updateParams({ view: '' })}+ aria-pressed={view === 'grid'}+ className={`inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium ${view === 'grid' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-300 hover:text-white'}`}+ >+ <LayoutGrid size={16} aria-hidden="true" /> Grid+ </button>+ <button+ type="button"+ onClick={() => updateParams({ view: 'albums' })}+ aria-pressed={view === 'albums'}+ className={`inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium ${view === 'albums' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-300 hover:text-white'}`}+ >+ <Library size={16} aria-hidden="true" /> Albums+ </button>+ </div><buttontype="button"onClick={handleSync}@@ -323,7 +518,7 @@ export default function Catalog() {<div className="flex flex-wrap items-center gap-2 mb-4"><buttontype="button"- onClick={() => setSelectedType('')}+ onClick={() => updateParams({ type: '' })}className={`text-xs px-3 py-1.5 rounded-full border ${selectedType === ''? 'bg-port-accent border-port-accent text-white'@@ -336,7 +531,7 @@ export default function Catalog() {<buttonkey={t.id}type="button"- onClick={() => setSelectedType(selectedType === t.id ? '' : t.id)}+ onClick={() => updateParams({ type: selectedType === t.id ? '' : t.id })}className={`text-xs px-3 py-1.5 rounded-full border ${selectedType === t.id? 'bg-port-accent border-port-accent text-white'@@ -348,6 +543,62 @@ export default function Catalog() {))}</div>+ {/* Universe / Series / Tag dropdowns + Clear filters. */}+ <div className="flex flex-wrap items-end gap-3 mb-4">+ <div>+ <label htmlFor="catalog-filter-universe" className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">Universe</label>+ <select+ id="catalog-filter-universe"+ value={selectedUniverse}+ // Changing universe clears a now-out-of-scope series selection.+ onChange={(e) => updateParams({ universe: e.target.value, series: '' })}+ className="px-3 py-2 bg-port-card border border-port-border rounded text-white text-sm min-w-[160px]"+ >+ <option value="">All universes</option>+ {(facets?.universes || []).map((u) => (+ <option key={u.refId} value={u.refId}>{u.name} ({u.count})</option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="catalog-filter-series" className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">Series</label>+ <select+ id="catalog-filter-series"+ value={selectedSeries}+ onChange={(e) => updateParams({ series: e.target.value })}+ className="px-3 py-2 bg-port-card border border-port-border rounded text-white text-sm min-w-[160px]"+ >+ <option value="">All series</option>+ {seriesOptions.map((s) => (+ <option key={s.refId} value={s.refId}>{s.name} ({s.count})</option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="catalog-filter-tag" className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">Tag</label>+ <select+ id="catalog-filter-tag"+ value={selectedTag}+ onChange={(e) => updateParams({ tag: e.target.value })}+ className="px-3 py-2 bg-port-card border border-port-border rounded text-white text-sm min-w-[140px]"+ >+ <option value="">All tags</option>+ {(facets?.tags || []).map((t) => (+ <option key={t.tag} value={t.tag}>{t.tag} ({t.count})</option>+ ))}+ </select>+ </div>+ {hasActiveFilters && (+ <button+ type="button"+ onClick={clearFilters}+ 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={14} aria-hidden="true" /> Clear filters+ </button>+ )}+ </div>+<div className="relative mb-6"><Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" aria-hidden="true" /><label htmlFor="catalog-search" className="sr-only">Search catalog</label>@@ -429,104 +680,58 @@ export default function Catalog() {</form>)}- {loading ? (+ {view === 'albums' ? (+ <AlbumsView+ key={dataVersion}+ facets={facets}+ cardProps={cardProps}+ onConfirmDelete={albumDelete}+ />+ ) : loading ? (<div className="text-gray-500 text-sm">Loading catalog…</div>) : items.length === 0 ? (<div className="bg-port-card border border-port-border rounded-lg p-8 text-center"><p className="text-sm text-gray-400">- {q || selectedType+ {hasActiveFilters? 'No ingredients match the current filter.': 'Your catalog is empty. Paste a scrap on the Ingest page or create one manually.'}</p></div>) : (- <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 + 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+ <>+ <div className="text-xs text-gray-500 mb-2">+ Showing {items.length}{hasMore ? '+' : ''}+ {knownTotal != null ? ` of ${knownTotal}` : ''}+ </div>+ <ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">+ {items.map((it) => (+ <CatalogCardkey={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'- }`}+ ingredient={it}+ getType={getType}+ selected={selectedIds.has(it.id)}+ onToggleSelect={toggleSelect}+ armed={armedId === it.id}+ onArm={setArmedId}+ onCancelArm={() => setArmedId(null)}+ onConfirmDelete={confirmDelete}+ />+ ))}+ </ul>+ {hasMore && (+ <div className="flex justify-center mt-4">+ <button+ type="button"+ onClick={loadMore}+ disabled={loadingMore}+ className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-white text-sm font-medium disabled:opacity-50">- <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 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">- <span className="block text-white font-medium truncate">{name}</span>- <span className="flex items-center gap-1.5 flex-wrap">- <TypeBadge type={it.type} getType={getType} />- {(it.tags || []).slice(0, 4).map((tag) => (- <span key={tag} className="text-[10px] px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-gray-400">- {tag}- </span>- ))}- </span>- {payloadSnippet(it.payload, it.type, 120, getType) ? (- <span className="text-xs text-gray-400 line-clamp-2">{payloadSnippet(it.payload, it.type, 120, getType)}</span>- ) : null}- </span>- </Link>- <div className="absolute top-2 right-2">- {/* The delete control is a sibling of the <Link>, not a- descendant, so a click on these buttons never traverses- the anchor — no preventDefault/stopPropagation needed. */}- {armed ? (- <span className="inline-flex items-center gap-1 text-xs bg-port-card border border-port-border rounded px-1 py-0.5 shadow-sm">- <span className="text-gray-400 pl-1">Delete?</span>- <button- type="button"- onClick={() => confirmDelete(it)}- className="px-2 py-0.5 rounded bg-port-error/20 text-port-error hover:bg-port-error/30 font-medium"- >- Yes- </button>- <button- type="button"- onClick={() => setArmedId(null)}- className="px-2 py-0.5 rounded text-gray-400 hover:text-white"- >- No- </button>- </span>- ) : (- <button- type="button"- onClick={() => setArmedId(it.id)}- className="p-1.5 rounded text-gray-500 hover:text-port-error bg-port-card"- aria-label={`Delete ${name}`}- title="Delete ingredient"- >- <Trash2 size={14} />- </button>- )}- </div>- </li>- );- })}- </ul>+ {loadingMore ? <Loader2 size={14} className="animate-spin" /> : null}+ Load more+ </button>+ </div>+ )}+ </>)}{selectedIds.size > 0 && (@@ -538,7 +743,7 @@ export default function Catalog() {<div className="relative"><buttontype="button"- onClick={() => setRemixMenuOpen((o) => !o)}+ onClick={() => { setRemixMenuOpen((o) => !o); setAddMenuOpen(false); }}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"@@ -566,6 +771,59 @@ export default function Catalog() {</ul>)}</div>+ <div className="relative">+ <button+ type="button"+ onClick={() => { setAddMenuOpen((o) => !o); setRemixMenuOpen(false); }}+ aria-haspopup="menu"+ aria-expanded={addMenuOpen}+ disabled={!hasRefTargets}+ title={hasRefTargets ? 'Place the selected ingredients into a universe or series' : 'No universes or series to place into yet'}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-port-border bg-port-card hover:bg-port-bg text-white text-sm font-medium disabled:opacity-50"+ >+ <FolderPlus size={16} aria-hidden="true" />+ Add to universe/series…+ </button>+ {addMenuOpen && hasRefTargets && (+ <div+ role="menu"+ className="absolute right-0 bottom-full mb-2 min-w-[220px] max-h-72 overflow-y-auto bg-port-card border border-port-border rounded-lg shadow-lg"+ >+ {refTargets.universes.length > 0 && (+ <>+ <p className="px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-gray-500">Universes</p>+ {refTargets.universes.map((t) => (+ <button+ key={`u-${t.refId}`}+ type="button"+ role="menuitem"+ onClick={() => handleAddToRef(t.refKind, t.refId, t.label)}+ className="w-full text-left px-3 py-2 text-sm text-gray-200 hover:bg-port-bg hover:text-white"+ >+ {t.label}+ </button>+ ))}+ </>+ )}+ {refTargets.series.length > 0 && (+ <>+ <p className="px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-gray-500">Series</p>+ {refTargets.series.map((t) => (+ <button+ key={`s-${t.refId}`}+ type="button"+ role="menuitem"+ onClick={() => handleAddToRef(t.refKind, t.refId, t.label)}+ className="w-full text-left px-3 py-2 text-sm text-gray-200 hover:bg-port-bg hover:text-white"+ >+ {t.label}+ </button>+ ))}+ </>+ )}+ </div>+ )}+ </div><buttontype="button"onClick={clearSelection}@@ -580,3 +838,58 @@ export default function Catalog() {</div>);}++// Albums grouped view (decision #1: flat universe albums + Raw + Orphaned).+// Album headers show counts from /facets up front; each album lazy-loads its+// cards the first time it is expanded. Mounted under a `key={dataVersion}` so a+// mutation remounts it and the lazy loads re-run against fresh data.+function AlbumsView({ facets, cardProps, onConfirmDelete }) {+ if (!facets) {+ return <div className="text-gray-500 text-sm">Loading albums…</div>;+ }+ const { universes = [], unlinkedCount = 0, orphanedCount = 0 } = facets;+ const albumProps = { ...cardProps, onConfirmDelete };+ const noAlbums = universes.length === 0 && unlinkedCount === 0 && orphanedCount === 0;+ if (noAlbums) {+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">+ <p className="text-sm text-gray-400">No albums yet — ingest or create ingredients to get started.</p>+ </div>+ );+ }+ return (+ <div className="space-y-3">+ {unlinkedCount > 0 && (+ <CatalogAlbum+ title="Unsorted / Raw"+ subtitle="not yet placed in a universe or series"+ count={unlinkedCount}+ defaultExpanded+ loadItems={() => listCatalogIngredients({ unlinked: true, limit: 200, silent: true })+ .then((d) => (Array.isArray(d?.items) ? d.items : []))}+ {...albumProps}+ />+ )}+ {universes.map((u) => (+ <CatalogAlbum+ key={u.refId}+ title={u.name}+ count={u.count}+ loadItems={() => listCatalogIngredients({ refKind: 'universe', refId: u.refId, limit: 200, silent: true })+ .then((d) => (Array.isArray(d?.items) ? d.items : []))}+ {...albumProps}+ />+ ))}+ {orphanedCount > 0 && (+ <CatalogAlbum+ title="Orphaned"+ subtitle="linked to a deleted universe/series — re-home these"+ count={orphanedCount}+ loadItems={() => listCatalogIngredients({ orphaned: true, limit: 200, silent: true })+ .then((d) => (Array.isArray(d?.items) ? d.items : []))}+ {...albumProps}+ />+ )}+ </div>+ );+}diff --git a/client/src/pages/Catalog.test.jsx b/client/src/pages/Catalog.test.jsxindex e58872322e..4b1cda9a06 100644--- a/client/src/pages/Catalog.test.jsx+++ b/client/src/pages/Catalog.test.jsx@@ -15,7 +15,9 @@ vi.mock('../services/apiCatalog', () => ({listCatalogIngredients: vi.fn(),createCatalogIngredient: vi.fn(),deleteCatalogIngredient: vi.fn(),+ linkCatalogIngredient: vi.fn(),getCatalogStats: vi.fn(),+ getCatalogFacets: vi.fn(),rerunCatalogMigration: vi.fn(),}));@@ -40,7 +42,9 @@ import {listCatalogIngredients,createCatalogIngredient,deleteCatalogIngredient,+ linkCatalogIngredient,getCatalogStats,+ getCatalogFacets,rerunCatalogMigration,} from '../services/apiCatalog';import { listCatalogTypes } from '../services/apiCatalogTypes';@@ -57,10 +61,22 @@ const renderCatalog = () => render(</MemoryRouter>,);+const sampleFacets = {+ types: [{ type: 'character', count: 1 }, { type: 'place', count: 1 }],+ universes: [{ refId: 'u-1', name: 'Echo Saints', count: 1 }],+ series: [{ refId: 's-1', name: 'Season 1', universeId: 'u-1', count: 1 }],+ tags: [{ tag: 'noir', count: 1 }],+ unlinkedCount: 1,+ orphanedCount: 0,+ total: 2,+};+beforeEach(() => {vi.clearAllMocks();- listCatalogIngredients.mockResolvedValue({ items: sample });+ listCatalogIngredients.mockResolvedValue({ items: sample, nextOffset: sample.length });+ linkCatalogIngredient.mockResolvedValue({ success: true });getCatalogStats.mockResolvedValue({ total: 2, byType: { character: 1, place: 1 } });+ getCatalogFacets.mockResolvedValue(sampleFacets);rerunCatalogMigration.mockResolvedValue({ stats: { promoted: 0 } });// Default: system registry only (the hook merges with the static fallback).listCatalogTypes.mockResolvedValue({ types: [] });@@ -284,4 +300,74 @@ describe('Catalog page', () => {// type-registry fetch resolves.await waitFor(() => expect(screen.getByRole('button', { name: /^Faction/i })).toBeTruthy());});++ it('filters by universe via the dropdown, passing a ref filter to the list fetch', async () => {+ renderCatalog();+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());++ fireEvent.change(screen.getByLabelText(/^Universe$/i), { target: { value: 'u-1' } });+ await waitFor(() => {+ expect(listCatalogIngredients).toHaveBeenLastCalledWith(+ expect.objectContaining({ refKind: 'universe', refId: 'u-1' }),+ );+ });+ });++ it('paginates with "Load more", appending the next page at the right offset', async () => {+ const firstPage = Array.from({ length: 60 }, (_, i) => ({+ id: `p-${i}`, name: `Item ${i}`, type: 'idea', payload: {}, tags: [],+ }));+ listCatalogIngredients+ .mockResolvedValueOnce({ items: firstPage, nextOffset: 60 })+ .mockResolvedValueOnce({ items: [{ id: 'p-60', name: 'Item 60', type: 'idea', payload: {}, tags: [] }], nextOffset: 61 });+ renderCatalog();+ await waitFor(() => expect(screen.getByText('Item 0')).toBeTruthy());++ const loadMore = screen.getByRole('button', { name: /Load more/i });+ await act(async () => { fireEvent.click(loadMore); });++ expect(listCatalogIngredients).toHaveBeenLastCalledWith(+ expect.objectContaining({ offset: 60 }),+ );+ await waitFor(() => expect(screen.getByText('Item 60')).toBeTruthy());+ });++ it('switches to the Albums view and lazy-loads the Raw album', async () => {+ renderCatalog();+ await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());++ fireEvent.click(screen.getByRole('button', { name: /^Albums$/i }));+ // Raw album is pinned + default-expanded → it fetches the unlinked set, and+ // the live universe album header shows from /facets.+ await waitFor(() => expect(screen.getByText('Unsorted / Raw')).toBeTruthy());+ expect(screen.getByText('Echo Saints')).toBeTruthy();+ await waitFor(() => {+ expect(listCatalogIngredients).toHaveBeenCalledWith(+ expect.objectContaining({ unlinked: true }),+ );+ });+ });++ it('bulk-places the selection into a universe with type-derived roles', async () => {+ 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.getByRole('button', { name: /Add to universe\/series/i }));+ await act(async () => {+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Echo Saints' }));+ });++ // character → cast-character, place → cast-place.+ expect(linkCatalogIngredient).toHaveBeenCalledWith(+ 'i-1', { refKind: 'universe', refId: 'u-1', role: 'cast-character' }, { silent: true },+ );+ expect(linkCatalogIngredient).toHaveBeenCalledWith(+ 'i-2', { refKind: 'universe', refId: 'u-1', role: 'cast-place' }, { silent: true },+ );+ expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/Added 2 ingredients to Echo Saints/i));+ });});diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.jsindex 5031d2908c..3fc45ed21f 100644--- a/client/src/services/apiCatalog.js+++ b/client/src/services/apiCatalog.js@@ -12,6 +12,10 @@ const enc = encodeURIComponent;export const getCatalogStats = (options) => request('/catalog/stats', options);+// Faceted counts (#1762) driving the filter dropdowns + album headers:+// { types, universes, series, tags, unlinkedCount, orphanedCount, total }.+export const getCatalogFacets = (options) => request('/catalog/facets', options);+// --- Scraps -------------------------------------------------------------export const createCatalogScrap = (body = {}, options) =>@@ -57,11 +61,22 @@ export const ingestCatalogBrain = (body = {}, options) =>// --- Ingredients ---------------------------------------------------------export const listCatalogIngredients = ({ type, tag, q, limit, offset, ...options } = {}) => {+export const listCatalogIngredients = ({ type, tag, q, refKind, refId, unlinked, orphaned, limit, offset, ...options } = {}) => {const params = new URLSearchParams();if (type) params.set('type', type);if (tag) params.set('tag', tag);if (q) params.set('q', q);+ // Album/facet filters (#1762). refKind/refId are a pair; unlinked/orphaned are+ // the "Raw"/"Orphaned" album views — mutually exclusive with each other and+ // with the ref filter (the server rejects combining them).+ if (refKind && refId) {+ params.set('refKind', refKind);+ params.set('refId', refId);+ } else if (unlinked) {+ params.set('unlinked', 'true');+ } else if (orphaned) {+ params.set('orphaned', 'true');+ }if (limit) params.set('limit', String(limit));if (offset) params.set('offset', String(offset));return request(`/catalog/ingredients${params.toString() ? `?${params}` : ''}`, options);diff --git a/client/src/services/apiCatalog.test.js b/client/src/services/apiCatalog.test.jsindex 7e6f26c36a..300b06e145 100644--- a/client/src/services/apiCatalog.test.js+++ b/client/src/services/apiCatalog.test.js@@ -48,3 +48,48 @@ describe('listCatalogIngredientsByIds', () => {expect(out.map((i) => i.id)).toEqual(['cat-a']);});});++describe('listCatalogIngredients filter passthrough (#1762)', () => {+ let listCatalogIngredients;+ beforeEach(async () => {+ ({ listCatalogIngredients } = await import('./apiCatalog.js'));+ request.mockResolvedValue({ items: [], nextOffset: 0 });+ });++ it('encodes a universe/series ref filter as refKind + refId', async () => {+ await listCatalogIngredients({ refKind: 'universe', refId: 'u-1', type: 'character' });+ const [path] = request.mock.calls[0];+ expect(decodeURIComponent(path)).toContain('refKind=universe');+ expect(decodeURIComponent(path)).toContain('refId=u-1');+ expect(decodeURIComponent(path)).toContain('type=character');+ });++ it('sends unlinked=true for the Raw album view', async () => {+ await listCatalogIngredients({ unlinked: true });+ const [path] = request.mock.calls[0];+ expect(path).toContain('unlinked=true');+ });++ it('sends orphaned=true for the Orphaned album view', async () => {+ await listCatalogIngredients({ orphaned: true });+ const [path] = request.mock.calls[0];+ expect(path).toContain('orphaned=true');+ });++ it('prefers the ref filter over unlinked/orphaned when both are passed', async () => {+ await listCatalogIngredients({ refKind: 'series', refId: 's-1', unlinked: true, orphaned: true });+ const [path] = request.mock.calls[0];+ expect(decodeURIComponent(path)).toContain('refKind=series');+ expect(path).not.toContain('unlinked');+ expect(path).not.toContain('orphaned');+ });+});++describe('getCatalogFacets (#1762)', () => {+ it('GETs the facets endpoint', async () => {+ const { getCatalogFacets } = await import('./apiCatalog.js');+ request.mockResolvedValue({ types: [], universes: [], series: [], tags: [], total: 0 });+ await getCatalogFacets();+ expect(request).toHaveBeenCalledWith('/catalog/facets', undefined);+ });+});diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex 65c4f42098..3bf657613a 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -35,6 +35,15 @@ export const INGREDIENT_TYPES = INGREDIENT_TYPE_IDS;const ingredientTypeGate = z.string().trim().min(1).max(32).refine(isActiveType, 'unknown ingredient type');+// Query-string booleans arrive as the strings 'true'/'false'. Coerce to a real+// boolean; anything else (including absent) collapses to undefined so an+// `.optional()` field reads cleanly as "not set" rather than truthy-by-presence.+const booleanish = z.preprocess((v) => {+ if (v === true || v === 'true') return true;+ if (v === false || v === 'false') return false;+ return undefined;+}, z.boolean());+export const REF_KINDS = Object.freeze(['universe','series',@@ -289,9 +298,29 @@ export const catalogIngredientQuerySchema = z.object({type: ingredientTypeGate.optional(),tag: tag.optional(),q: z.string().trim().max(500).optional(),+ // Album/facet filters (#1762). `refKind`+`refId` list ingredients linked to a+ // universe/series; `unlinked` = the "Raw" album (no universe/series ref at+ // all); `orphaned` = the "Orphaned" album (has a ref, none resolve live). The+ // wire form sends booleans as `?unlinked=true`, so coerce the string here.+ refKind: z.enum(REF_KINDS).optional(),+ refId: z.string().trim().min(1).max(120).optional(),+ unlinked: booleanish.optional(),+ orphaned: booleanish.optional(),limit: z.coerce.number().int().min(1).max(200).optional(),offset: z.coerce.number().int().min(0).optional(),-}).strict();+}).strict()+ // refKind/refId are a pair — one without the other is a malformed query.+ .refine((v) => (v.refKind == null) === (v.refId == null), {+ message: 'refKind and refId must be supplied together',+ path: ['refId'],+ })+ // The three album filters are mutually exclusive — combining them is ambiguous+ // (a ref-filtered row is by definition linked, so it can never be unlinked/+ // orphaned). Reject rather than silently letting one win in the service.+ .refine((v) => [v.refKind != null, v.unlinked === true, v.orphaned === true].filter(Boolean).length <= 1, {+ message: 'refKind/refId, unlinked, and orphaned are mutually exclusive',+ path: ['unlinked'],+ });// Tag-autocomplete query — `q` is an optional prefix/substring filter, absent// returns the most-recently-created tags. Drives the tag-picker autocomplete ondiff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.jsindex e78b0fa8a4..21d5188fbd 100644--- a/server/lib/catalogValidation.test.js+++ b/server/lib/catalogValidation.test.js@@ -241,6 +241,33 @@ describe('catalogValidation — catalogIngredientQuerySchema', () => {it('rejects an oversized single id token (>64 chars)', () => {expect(() => catalogIngredientQuerySchema.parse({ ids: 'x'.repeat(65) })).toThrow();});++ // --- Album/facet filters (#1762) ---+ it('accepts a paired refKind + refId', () => {+ const out = catalogIngredientQuerySchema.parse({ refKind: 'universe', refId: 'u-1' });+ expect(out.refKind).toBe('universe');+ expect(out.refId).toBe('u-1');+ });++ it('rejects refKind without refId (and vice versa)', () => {+ expect(() => catalogIngredientQuerySchema.parse({ refKind: 'universe' })).toThrow();+ expect(() => catalogIngredientQuerySchema.parse({ refId: 'u-1' })).toThrow();+ });++ it('coerces unlinked/orphaned booleanish strings', () => {+ expect(catalogIngredientQuerySchema.parse({ unlinked: 'true' }).unlinked).toBe(true);+ expect(catalogIngredientQuerySchema.parse({ orphaned: 'true' }).orphaned).toBe(true);+ expect(catalogIngredientQuerySchema.parse({ unlinked: 'false' }).unlinked).toBe(false);+ });++ it('rejects combining the three album filters', () => {+ expect(() => catalogIngredientQuerySchema.parse({ refKind: 'universe', refId: 'u-1', unlinked: 'true' })).toThrow();+ expect(() => catalogIngredientQuerySchema.parse({ unlinked: 'true', orphaned: 'true' })).toThrow();+ });++ it('rejects an unknown refKind', () => {+ expect(() => catalogIngredientQuerySchema.parse({ refKind: 'galaxy', refId: 'g-1' })).toThrow();+ });});describe('catalogValidation — catalogIngredientLinkSchema', () => {diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex fc343e0941..5808d10c38 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -200,11 +200,22 @@ router.get('/ingredients', asyncHandler(async (req, res) => {type: params.type,tag: params.tag,query: params.q,+ refKind: params.refKind,+ refId: params.refId,+ unlinked: params.unlinked === true,+ orphaned: params.orphaned === true,limit: params.limit ?? 50,offset: params.offset ?? 0,}));}));+// Faceted counts for the Catalog filter dropdowns + album headers (#1762):+// type/universe/series/tag facets plus the unlinked ("Raw") and orphaned bucket+// counts, in one round-trip. Live universes/series only.+router.get('/facets', asyncHandler(async (_req, res) => {+ res.json(await catalogDB.getCatalogFacets());+}));+router.get('/ingredients/:id', asyncHandler(async (req, res) => {const ing = await catalogDB.getIngredient(req.params.id);if (!ing) throw new ServerError('Ingredient not found', { status: 404 });diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.jsindex 2b815459ec..0e5544316c 100644--- a/server/routes/catalog.test.js+++ b/server/routes/catalog.test.js@@ -19,7 +19,7 @@ import { describe, it, expect, afterAll, vi } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';-import { checkHealth, ensureSchema, close } from '../lib/db.js';+import { checkHealth, ensureSchema, close, query } from '../lib/db.js';// Mock embeddings — the bulk-import + restore routes call these; we don't want a// network round-trip and the assertions never inspect the vector.@@ -277,3 +277,46 @@ describe.skipIf(!dbReady)('GET /api/catalog/ingredients/:id/details — batchedexpect(r.status).toBe(404);});});++describe.skipIf(!dbReady)('GET /api/catalog/facets + ingredient filters (#1762)', () => {+ const UNI = `route-uni-${NONCE}`;+ afterAll(async () => {+ await query('DELETE FROM catalog_ingredient_refs WHERE ref_id = $1', [UNI]).catch(() => {});+ await query('DELETE FROM universes WHERE id = $1', [UNI]).catch(() => {});+ });++ it('returns the facets envelope with universe membership + bucket counts', async () => {+ await query('INSERT INTO universes (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING', [UNI, `Route Universe ${NONCE}`]);+ const linked = await catalogDB.createIngredient({ type: 'character', name: `Route Linked ${NONCE}`, tags: [`rt-${NONCE}`] });+ const raw = await catalogDB.createIngredient({ type: 'idea', name: `Route Raw ${NONCE}` });+ createdIngredientIds.add(linked.id);+ createdIngredientIds.add(raw.id);+ await catalogDB.linkIngredientToRef(linked.id, 'universe', UNI, 'cast-character');++ const r = await request(makeApp()).get('/api/catalog/facets');+ expect(r.status).toBe(200);+ expect(Array.isArray(r.body.types)).toBe(true);+ expect(Array.isArray(r.body.universes)).toBe(true);+ expect(Array.isArray(r.body.tags)).toBe(true);+ expect(typeof r.body.total).toBe('number');+ expect(typeof r.body.unlinkedCount).toBe('number');+ expect(typeof r.body.orphanedCount).toBe('number');+ const uni = r.body.universes.find((u) => u.refId === UNI);+ expect(uni?.name).toBe(`Route Universe ${NONCE}`);+ expect(uni?.count).toBeGreaterThanOrEqual(1);++ // The ref filter lists only the linked ingredient.+ const filtered = await request(makeApp()).get(`/api/catalog/ingredients?refKind=universe&refId=${UNI}`);+ expect(filtered.status).toBe(200);+ const ids = filtered.body.items.map((i) => i.id);+ expect(ids).toContain(linked.id);+ expect(ids).not.toContain(raw.id);+ });++ it('400s on an unpaired refKind and on combined album filters', async () => {+ const noRefId = await request(makeApp()).get('/api/catalog/ingredients?refKind=universe');+ expect(noRefId.status).toBe(400);+ const combined = await request(makeApp()).get('/api/catalog/ingredients?unlinked=true&orphaned=true');+ expect(combined.status).toBe(400);+ });+});diff --git a/server/services/catalogDB.facets.db.test.js b/server/services/catalogDB.facets.db.test.jsnew file mode 100644index 0000000000..8c9a19b8f6--- /dev/null+++ b/server/services/catalogDB.facets.db.test.js@@ -0,0 +1,157 @@+/**+ * Postgres-backed tests for the Catalog facet + album filters (#1762):+ * - listIngredients({ refKind, refId }) — universe/series membership+ * - listIngredients({ unlinked: true }) — the "Raw" album (no u/s ref)+ * - listIngredients({ orphaned: true }) — refs whose target is gone+ * - getCatalogFacets() — type/universe/series/tag facets ++ * unlinked / orphaned bucket counts+ *+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`, never+ * the real `portos` DB (the db.js runner guard + the suite skip below enforce+ * this). The DB is shared across worktrees, so assertions are RELATIVE+ * (membership + `>=`) and every row created here is torn down in afterAll.+ */++import { describe, it, expect, afterAll, beforeAll } from 'vitest';+import { checkHealth, ensureSchema, close, query } from '../lib/db.js';+import * as catalogDB from './catalogDB.js';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ const recheck = await checkHealth().catch(() => ({ hasCatalogSchema: false }));+ if (recheck.hasCatalogSchema) dbReady = true;+ else skipReason = 'catalog schema not present';+ }+}+if (!dbReady) console.log(`⏭️ catalogDB.facets.db.test: skipping suite — ${skipReason || 'no database'}`);++const nonce = `f${Date.now()}`;+const UNI_ID = `uni-${nonce}`;+const SER_ID = `ser-${nonce}`;+const DEAD_UNI_ID = `dead-uni-${nonce}`; // never inserted → orphaned target+const TAG = `tag-${nonce}`;+const createdIngredientIds = new Set();++beforeAll(async () => {+ if (!dbReady) return;+ await query('INSERT INTO universes (id, name) VALUES ($1, $2)', [UNI_ID, `Universe ${nonce}`]);+ await query('INSERT INTO pipeline_series (id, name, universe_id) VALUES ($1, $2, $3)', [SER_ID, `Series ${nonce}`, UNI_ID]);+});++afterAll(async () => {+ if (!dbReady) return;+ for (const id of createdIngredientIds) {+ await catalogDB.deleteIngredient(id, { hard: true }).catch(() => {});+ }+ await query('DELETE FROM catalog_ingredient_refs WHERE ref_id = ANY($1)', [[UNI_ID, SER_ID, DEAD_UNI_ID]]).catch(() => {});+ await query('DELETE FROM pipeline_series WHERE id = $1', [SER_ID]).catch(() => {});+ await query('DELETE FROM universes WHERE id = $1', [UNI_ID]).catch(() => {});+ await close();+});++describe.skipIf(!dbReady)('catalogDB facets + album filters (#1762)', () => {+ it('lists ingredients by universe ref (membership), composing with type', async () => {+ const linked = await catalogDB.createIngredient({ type: 'character', name: `Linked ${nonce}`, tags: [TAG] });+ const other = await catalogDB.createIngredient({ type: 'place', name: `Other ${nonce}` });+ createdIngredientIds.add(linked.id);+ createdIngredientIds.add(other.id);+ await catalogDB.linkIngredientToRef(linked.id, 'universe', UNI_ID, 'cast-character');++ const { items } = await catalogDB.listIngredients({ refKind: 'universe', refId: UNI_ID, limit: 200 });+ const ids = items.map((i) => i.id);+ expect(ids).toContain(linked.id);+ expect(ids).not.toContain(other.id);++ // Composes with a type filter (still matches, since linked is a character).+ const typed = await catalogDB.listIngredients({ refKind: 'universe', refId: UNI_ID, type: 'character', limit: 200 });+ expect(typed.items.map((i) => i.id)).toContain(linked.id);+ // …and excludes when the type doesn't match.+ const typedMiss = await catalogDB.listIngredients({ refKind: 'universe', refId: UNI_ID, type: 'object', limit: 200 });+ expect(typedMiss.items.map((i) => i.id)).not.toContain(linked.id);+ });++ it('does not duplicate a row linked under multiple roles', async () => {+ const multi = await catalogDB.createIngredient({ type: 'character', name: `Multi ${nonce}` });+ createdIngredientIds.add(multi.id);+ await catalogDB.linkIngredientToRef(multi.id, 'universe', UNI_ID, 'cast-character');+ await catalogDB.linkIngredientToRef(multi.id, 'universe', UNI_ID, 'reference');++ const { items } = await catalogDB.listIngredients({ refKind: 'universe', refId: UNI_ID, limit: 200 });+ const occurrences = items.filter((i) => i.id === multi.id).length;+ expect(occurrences).toBe(1);+ });++ it('lists unlinked ("Raw") ingredients and excludes linked ones', async () => {+ const raw = await catalogDB.createIngredient({ type: 'idea', name: `Raw ${nonce}` });+ const linked = await catalogDB.createIngredient({ type: 'character', name: `RawLinked ${nonce}` });+ createdIngredientIds.add(raw.id);+ createdIngredientIds.add(linked.id);+ await catalogDB.linkIngredientToRef(linked.id, 'series', SER_ID, 'cast-character');++ const { items } = await catalogDB.listIngredients({ unlinked: true, limit: 1000 });+ const ids = items.map((i) => i.id);+ expect(ids).toContain(raw.id);+ expect(ids).not.toContain(linked.id);+ });++ it('lists orphaned ingredients (ref present, target gone) and excludes live-linked', async () => {+ const orphan = await catalogDB.createIngredient({ type: 'object', name: `Orphan ${nonce}` });+ const live = await catalogDB.createIngredient({ type: 'object', name: `Live ${nonce}` });+ createdIngredientIds.add(orphan.id);+ createdIngredientIds.add(live.id);+ // orphan → points at a universe id that has no row; live → the real universe.+ await catalogDB.linkIngredientToRef(orphan.id, 'universe', DEAD_UNI_ID, 'reference');+ await catalogDB.linkIngredientToRef(live.id, 'universe', UNI_ID, 'reference');++ const { items } = await catalogDB.listIngredients({ orphaned: true, limit: 1000 });+ const ids = items.map((i) => i.id);+ expect(ids).toContain(orphan.id);+ expect(ids).not.toContain(live.id);+ // An orphan is, by definition, NOT in the unlinked set (it has a ref).+ const raw = await catalogDB.listIngredients({ unlinked: true, limit: 1000 });+ expect(raw.items.map((i) => i.id)).not.toContain(orphan.id);+ });++ it('getCatalogFacets aggregates type/universe/series/tag facets + bucket counts', async () => {+ const linked = await catalogDB.createIngredient({ type: 'character', name: `FacetLinked ${nonce}`, tags: [TAG] });+ const seriesLinked = await catalogDB.createIngredient({ type: 'character', name: `FacetSeries ${nonce}` });+ const raw = await catalogDB.createIngredient({ type: 'idea', name: `FacetRaw ${nonce}` });+ const orphan = await catalogDB.createIngredient({ type: 'object', name: `FacetOrphan ${nonce}` });+ [linked, seriesLinked, raw, orphan].forEach((i) => createdIngredientIds.add(i.id));+ await catalogDB.linkIngredientToRef(linked.id, 'universe', UNI_ID, 'cast-character');+ await catalogDB.linkIngredientToRef(seriesLinked.id, 'series', SER_ID, 'cast-character');+ await catalogDB.linkIngredientToRef(orphan.id, 'universe', DEAD_UNI_ID, 'reference');++ const facets = await catalogDB.getCatalogFacets();++ // Live universe + series appear with their resolved names + counts.+ const uni = facets.universes.find((u) => u.refId === UNI_ID);+ expect(uni).toBeTruthy();+ expect(uni.name).toBe(`Universe ${nonce}`);+ expect(uni.count).toBeGreaterThanOrEqual(1);++ const ser = facets.series.find((s) => s.refId === SER_ID);+ expect(ser).toBeTruthy();+ expect(ser.name).toBe(`Series ${nonce}`);+ expect(ser.universeId).toBe(UNI_ID);+ expect(ser.count).toBeGreaterThanOrEqual(1);++ // A dangling-target universe never appears in the live facet array.+ expect(facets.universes.find((u) => u.refId === DEAD_UNI_ID)).toBeUndefined();++ // Tag + type facets surface our nonce tag and the character type.+ expect(facets.tags.find((t) => t.tag === TAG)?.count).toBeGreaterThanOrEqual(1);+ expect(facets.types.find((t) => t.type === 'character')?.count).toBeGreaterThanOrEqual(2);++ // Bucket counts: our raw + orphan each push their bucket up by >=1.+ expect(facets.unlinkedCount).toBeGreaterThanOrEqual(1);+ expect(facets.orphanedCount).toBeGreaterThanOrEqual(1);+ expect(facets.total).toBeGreaterThanOrEqual(4);+ });+});diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex 0dec4e8609..e57c23bf41 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -700,7 +700,24 @@ const THUMBNAIL_KEY_SUBQUERY = `(LIMIT 1) AS thumbnail_key`;-export async function listIngredients({ ids, type, tag, query: q, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {+// SQL predicate matching ingredients that have at least one LIVE universe/series+// ref (target row still resolves). Hardcodes the universe/series live clauses —+// both are `deleted = FALSE` in REF_TARGET_TABLES (catalogRefResolver.js); kept+// inline rather than imported because each kind probes a different target table.+const HAS_LIVE_UNIVERSE_SERIES_REF = `EXISTS (+ SELECT 1 FROM catalog_ingredient_refs r+ WHERE r.ingredient_id = catalog_ingredients.id AND r.deleted = false+ AND ((r.ref_kind = 'universe' AND EXISTS (SELECT 1 FROM universes u WHERE u.id = r.ref_id AND u.deleted = false))+ OR (r.ref_kind = 'series' AND EXISTS (SELECT 1 FROM pipeline_series s WHERE s.id = r.ref_id AND s.deleted = false))))`;++// At least one universe/series ref row exists (live OR dangling) — distinguishes+// "orphaned" (has a ref, none resolve) from "unlinked" (no ref at all).+const HAS_ANY_UNIVERSE_SERIES_REF = `EXISTS (+ SELECT 1 FROM catalog_ingredient_refs r+ WHERE r.ingredient_id = catalog_ingredients.id AND r.deleted = false+ AND r.ref_kind IN ('universe', 'series'))`;++export async function listIngredients({ ids, type, tag, query: q, refKind = null, refId = null, unlinked = false, orphaned = false, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {const conditions = ['deleted = false'];const params = [];let idx = 1;@@ -726,6 +743,23 @@ export async function listIngredients({ ids, type, tag, query: q, limit = 50, ofconditions.push(`search_tsv @@ websearch_to_tsquery('english', $${qIdx})`);params.push(q);}+ // Album/facet filters (#1762). EXISTS subquery (not a JOIN) so a row linked+ // under multiple roles isn't duplicated — no DISTINCT needed. Composes with+ // type/tag/q above. `unlinked` and `orphaned` are mutually exclusive views+ // of the un-homed set; the route schema rejects combining them with ref.+ if (refKind && refId) {+ conditions.push(`EXISTS (SELECT 1 FROM catalog_ingredient_refs r+ WHERE r.ingredient_id = catalog_ingredients.id AND r.deleted = false+ AND r.ref_kind = $${idx++} AND r.ref_id = $${idx++})`);+ params.push(refKind, refId);+ } else if (unlinked) {+ // "Unsorted / Raw": no universe/series ref at all.+ conditions.push(`NOT ${HAS_ANY_UNIVERSE_SERIES_REF}`);+ } else if (orphaned) {+ // "Orphaned": has a universe/series ref, but none resolve to a live target.+ conditions.push(HAS_ANY_UNIVERSE_SERIES_REF);+ conditions.push(`NOT ${HAS_LIVE_UNIVERSE_SERIES_REF}`);+ }}if (embeddingMissing) {conditions.push('embedding IS NULL');@@ -1704,3 +1738,65 @@ export async function getCatalogStats() {withEmbeddings: parseInt(withEmb.rows[0].count, 10),};}++// Faceted counts driving the Catalog filter dropdowns + album headers (#1762)+// in one round-trip. Distinguishes three mutually-exclusive per-ingredient+// buckets: LINKED (≥1 live universe/series ref — rolls up into the universes/+// series facet arrays), UNLINKED (no universe/series ref at all → "Raw" album),+// and ORPHANED (has a universe/series ref but none resolve to a live target →+// "Orphaned" album). Only live universes/series appear in the facet arrays; the+// joins on `deleted = false` enforce the same live predicate the resolver uses.+export async function getCatalogFacets() {+ const [typeRows, uniRows, serRows, tagRows, bucketRows] = await Promise.all([+ query(`SELECT type, COUNT(*)::int AS count+ FROM catalog_ingredients WHERE deleted = false+ GROUP BY type ORDER BY count DESC, type`),+ query(`SELECT u.id AS ref_id, u.name, COUNT(DISTINCT r.ingredient_id)::int AS count+ FROM catalog_ingredient_refs r+ JOIN catalog_ingredients i ON i.id = r.ingredient_id AND i.deleted = false+ JOIN universes u ON u.id = r.ref_id AND u.deleted = false+ WHERE r.deleted = false AND r.ref_kind = 'universe'+ GROUP BY u.id, u.name ORDER BY count DESC, u.name`),+ query(`SELECT s.id AS ref_id, s.name, s.universe_id, COUNT(DISTINCT r.ingredient_id)::int AS count+ FROM catalog_ingredient_refs r+ JOIN catalog_ingredients i ON i.id = r.ingredient_id AND i.deleted = false+ JOIN pipeline_series s ON s.id = r.ref_id AND s.deleted = false+ WHERE r.deleted = false AND r.ref_kind = 'series'+ GROUP BY s.id, s.name, s.universe_id ORDER BY count DESC, s.name`),+ query(`SELECT tag, COUNT(*)::int AS count+ FROM (SELECT unnest(tags) AS tag FROM catalog_ingredients WHERE deleted = false) t+ GROUP BY tag ORDER BY count DESC, tag`),+ // Per-ingredient bucket classification. ref_count = live universe/series ref+ // ROWS; live_count = those whose target still resolves. unlinked = ref_count 0;+ // orphaned = ref_count > 0 but live_count 0; linked = live_count > 0.+ query(`SELECT+ COUNT(*) FILTER (WHERE ref_count = 0)::int AS unlinked,+ COUNT(*) FILTER (WHERE ref_count > 0 AND live_count = 0)::int AS orphaned,+ COUNT(*) FILTER (WHERE live_count > 0)::int AS linked+ FROM (+ SELECT i.id,+ COUNT(r.ref_id) AS ref_count,+ COUNT(r.ref_id) FILTER (WHERE+ (r.ref_kind = 'universe' AND EXISTS (SELECT 1 FROM universes u WHERE u.id = r.ref_id AND u.deleted = false))+ OR (r.ref_kind = 'series' AND EXISTS (SELECT 1 FROM pipeline_series s WHERE s.id = r.ref_id AND s.deleted = false))+ ) AS live_count+ FROM catalog_ingredients i+ LEFT JOIN catalog_ingredient_refs r+ ON r.ingredient_id = i.id AND r.deleted = false AND r.ref_kind IN ('universe', 'series')+ WHERE i.deleted = false+ GROUP BY i.id+ ) sub`),+ ]);+ const types = typeRows.rows.map((r) => ({ type: r.type, count: r.count }));+ const total = types.reduce((sum, t) => sum + t.count, 0);+ const buckets = bucketRows.rows[0] || {};+ return {+ types,+ universes: uniRows.rows.map((r) => ({ refId: r.ref_id, name: r.name, count: r.count })),+ series: serRows.rows.map((r) => ({ refId: r.ref_id, name: r.name, universeId: r.universe_id, count: r.count })),+ tags: tagRows.rows.map((r) => ({ tag: r.tag, count: r.count })),+ unlinkedCount: buckets.unlinked ?? 0,+ orphanedCount: buckets.orphaned ?? 0,+ total,+ };+}diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 6d06cab9a6..87b4d25b71 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -10,6 +10,7 @@ import { defineConfig } from 'vitest/config';export const DB_TEST_INCLUDE = ['**/db.test.js','services/catalogDB.test.js',+ 'services/catalogDB.facets.db.test.js','services/catalogCanonProjection.test.js','services/catalogRefResolver.test.js','services/creativeDirector/projectsDB.test.js',