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
catalog: editable character sheet on the detail page + friendly universe tags for backfilled rows
[._.]/ Adam Eivy065adbaca0a3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 595fc52b8a..d8347974fa 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -15,6 +15,7 @@- **[catalog-federation-orchestrator] The creative catalog now auto-replicates between peers.** The catalog sync routes existed but nothing pulled from peers — orphan ingredients (ideas / scenes / concepts not attached to a universe) and the universe→ingredient ref links stayed local. The sync orchestrator now runs `catalog` as a delta-based PostgreSQL category alongside Memory: on every peer-online event and on the background interval it pulls `GET /api/catalog/sync` (the seven independent per-kind BIGSERIAL cursors: scraps / ingredients / sources / refs / relations / tags / media) and applies each batch locally with the same last-writer-wins + per-row isolation + schema-version gate as direct sync. A peer ahead on the `catalog` schema records a gap on the Instances page (the existing SchemaGapBadge) and pauses draining instead of looping. Toggle it per peer under Instances → Sync Categories → "Catalog"; Postgres-only (a non-Postgres peer simply never enables it).- **[catalog-bundled-universe-push] Universe peer-pushes now carry their catalog enrichments.** When peer A pushes a universe to peer B, the push bundles the `catalog_ingredients` rows referenced by that universe's canon plus the universe→ingredient ref links. Previously only the embedded canon replicated, so the receiver re-derived a strictly-lossy view on first backfill — the `tags`, vector `embedding`, and `payload.summary`-style enrichments that live only in the catalog row were dropped. The bundle ships the full enriched rows (including tombstoned ref rows so unlinks propagate), applied through the same catalog-sync path; it rides only universe pushes (never series / mediaCollection), skips tombstone pushes, and is gated by `PORTOS_SCHEMA_VERSIONS.catalog` so a receiver on an older catalog schema rejects a forward-shaped bundle with a clean 409 rather than corrupting local rows. Postgres-only and best-effort — a bundle failure never fails the universe push.+- **[catalog-character-sheet-enrichment] The Catalog character detail page is now a full editable character sheet, and backfilled rows get friendly universe tags.** Opening a `character` ingredient (e.g. `/catalog/character/cat-chr-…`) now shows grouped DnD-style sheet sections — Identity, Appearance, Personality & Voice, Goals & Drives, Background & Relationships, Notes — exposing every enriched canon scalar field the Universe Builder already tracks (role/archetype, pronouns, age, core theme, physical description, visual/silhouette/posture notes, special traits, personality, mannerisms, speech accent/pattern, motivations, likes, dislikes/fears, background, relationships, skills). Because the editor keys mirror `sanitizeCharacter` exactly, an edit on the Catalog surface lands in the same payload field the Universe Builder canon surface reads — the two are the same durable row (linked by the embedded `ingredientId` + `catalog_ingredient_refs`). The catalog's enriched array fields (color palette swatches, stats, aliases) render read-only here (their structured per-item editors live in Universe Builder), and a new "Reference sheet" panel shows the rendered turnaround when one exists (`/data/image-refs/…`) or, when the character belongs to a universe, links straight to Universe Builder to render one from that universe's style data. Places and objects get the same grouped-section treatment. Migration: a one-time boot-time data repair rewrites the legacy machine tags backfilled rows carried (`from-universe`, `universe:<uuid>`) into the friendly universe NAME tag while preserving every user tag and the structured universe ref — marker-gated in `data/catalog-universe-tags.applied.json` and registered in the migration ledger as `053-catalog-friendly-universe-tags`; new bible→catalog promotions stamp the friendly name from the start. (The deeper unification — collapsing the embedded canon entry to a pure `ingredientId` projection so the catalog row is the single store of record — is scoped to follow.)- **[catalog-ingredient-media-refs] Catalog ingredients can now carry typed media attachments — a portrait, mood/reference images, and more.** A new "Media" panel on each ingredient detail page lets you set one portrait (rendered large at the head) and attach additional reference images, scoped to your existing media gallery via a "Pick from gallery" picker or by dragging a gallery image onto the panel. Each attachment stores a `media_key` *reference* into your media library (the bytes are never duplicated into the catalog), so a federated peer that receives an ingredient gets its media-key list and matches it against its own library — keys whose asset hasn't arrived yet show a "missing" badge (via the same syncing-asset surface used elsewhere) instead of a broken image. Backed by a new `catalog_ingredient_media` Postgres table (kinds: portrait / reference / audio / video / document) with soft-delete tombstones from day one, so detaches propagate to peers; the rows ride the catalog sync envelope as a new `media` block (`PORTOS_SCHEMA_VERSIONS.catalog` bumped to 6 — a peer on an older catalog schema gets a clean 412 rather than silently dropping every attachment). `POST/DELETE /api/catalog/ingredients/:id/media`, `POST …/media/portrait`, and `GET …/media` + `…/media/missing` are Zod-validated; attaching rejects a key that doesn't resolve against the local library with a 422. Voice-memo capture is intentionally left as a clean seam for the separate source-kinds work.diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.jsindex 16d48ba32a..bde37d7c64 100644--- a/client/src/lib/catalogTypes.js+++ b/client/src/lib/catalogTypes.js@@ -24,6 +24,141 @@ const LIGHT_FIELDS = [['notes', 'Notes', 'textarea'],];+// Grouped "character sheet" layout for the rich canon types+// (character/place/object). Each section is `{ title, fields }` where `fields`+// is the same `[key, label, kind]` tuple list as `editorFields`. The CatalogIngredient+// detail editor renders `editorSections` as collapsible DnD-style sheet+// sections when present, and falls back to the flat `editorFields` list for+// the light types. The keys mirror the canon sanitizers in+// `server/lib/storyBible.js` (`sanitizeCharacter`/`sanitizePlace`/`sanitizeObject`)+// EXACTLY so an edit on the Catalog surface lands in the same payload field the+// Universe Builder canon surface reads — the two are the same durable record.+//+// Complex array fields (stats[], colorPalette[], props[], expressions[],+// handGestures[], wardrobes[], imageRefs[]) are intentionally NOT in these+// scalar sections — they are surfaced read-only by the sheet (see+// CHARACTER_LIST_FIELDS / CHARACTER_IMAGE_FIELDS) and remain editable on the+// Universe Builder canon surface where their structured editors live.+const CHARACTER_SECTIONS = [+ {+ title: 'Identity',+ fields: [+ ['role', 'Role / Archetype', 'text'],+ ['pronouns', 'Pronouns', 'text'],+ ['age', 'Age', 'text'],+ ['coreTheme', 'Core Theme', 'text'],+ ],+ },+ {+ title: 'Appearance',+ fields: [+ ['physicalDescription', 'Physical Description', 'textarea'],+ ['visualNotes', 'Visual Notes', 'textarea'],+ ['visualIdentity', 'Visual Identity', 'textarea'],+ ['silhouetteNotes', 'Silhouette Notes', 'textarea'],+ ['postureNotes', 'Posture Notes', 'textarea'],+ ['specialTraits', 'Special Traits', 'textarea'],+ ],+ },+ {+ title: 'Personality & Voice',+ fields: [+ ['personality', 'Personality', 'textarea'],+ ['mannerisms', 'Mannerisms', 'textarea'],+ ['speechAccent', 'Speech Accent', 'text'],+ ['speechPattern', 'Speech Pattern', 'textarea'],+ ],+ },+ {+ title: 'Goals & Drives',+ fields: [+ ['motivations', 'Motivations / Goals', 'textarea'],+ ['likes', 'Likes', 'textarea'],+ ['dislikes', 'Dislikes / Fears', 'textarea'],+ ],+ },+ {+ title: 'Background & Relationships',+ fields: [+ ['background', 'Background', 'textarea'],+ ['relationships', 'Relationships', 'textarea'],+ ['skills', 'Skills / Abilities', 'textarea'],+ ],+ },+ {+ title: 'Notes',+ fields: [+ ['notes', 'Notes', 'textarea'],+ ],+ },+];++const PLACE_SECTIONS = [+ {+ title: 'Identity',+ fields: [+ ['slugline', 'Slugline', 'text'],+ ['era', 'Era', 'text'],+ ['weather', 'Weather', 'text'],+ ],+ },+ {+ title: 'Appearance',+ fields: [+ ['description', 'Description', 'textarea'],+ ['palette', 'Color Palette', 'textarea'],+ ['recurringDetails', 'Recurring Details', 'textarea'],+ ],+ },+ {+ title: 'Notes',+ fields: [+ ['notes', 'Notes', 'textarea'],+ ],+ },+];++const OBJECT_SECTIONS = [+ {+ title: 'Identity',+ fields: [+ ['description', 'Description', 'textarea'],+ ],+ },+ {+ title: 'Significance',+ fields: [+ ['significance', 'Significance', 'textarea'],+ ],+ },+ {+ title: 'Notes',+ fields: [+ ['notes', 'Notes', 'textarea'],+ ],+ },+];++// Flatten a section list back into the legacy `[key, label, kind]` flat list.+// `editorFields` stays the canonical flat enumeration used by the revision-diff+// builder + any consumer that just wants "every editable scalar key"; the+// sections are an additional grouped VIEW over the same fields.+function flattenSections(sections) {+ return sections.flatMap((s) => s.fields);+}++// Read-only array fields surfaced by the character sheet. These are edited on+// the Universe Builder canon surface (structured per-item editors live there);+// the Catalog sheet renders them as labeled chips/cards so the enriched canon+// is visible without leaving the page. `kind` drives the renderer:+// 'colorPalette' → swatch row ({ name, hex }); 'kv' → key/value stat rows+// ({ key, value }); 'text' → string-array chips.+export const CHARACTER_LIST_FIELDS = Object.freeze([+ { key: 'aliases', label: 'Aliases', kind: 'text' },+ { key: 'colorPalette', label: 'Color Palette', kind: 'colorPalette' },+ { key: 'stats', label: 'Stats', kind: 'kv' },+]);+export const CATALOG_TYPES = Object.freeze([{id: 'character',@@ -32,18 +167,12 @@ export const CATALOG_TYPES = Object.freeze([primaryContentKey: 'physicalDescription',primaryContentLabel: 'Physical Description',snippetFallbackKeys: ['physicalDescription', 'description', 'summary', 'personality', 'significance', 'role', 'notes'],- editorFields: [- ['role', 'Role', 'text'],- // Canon character shape uses `physicalDescription` (matches- // sanitizeCharacter and the writers-room/bible extractor). A plain- // `description` here would render empty for backfill-promoted characters- // and edits would land in a sibling field the canon doesn't read.- ['physicalDescription', 'Physical Description', 'textarea'],- ['personality', 'Personality', 'textarea'],- ['background', 'Background', 'textarea'],- ['motivations', 'Motivations', 'textarea'],- ['notes', 'Notes', 'textarea'],- ],+ // Grouped DnD-style sheet sections (rendered by CatalogIngredient). Keys+ // mirror `sanitizeCharacter` in server/lib/storyBible.js EXACTLY so a+ // Catalog-surface edit lands in the same canon field the Universe Builder+ // reads. `editorFields` is the flattened enumeration of these same keys.+ editorSections: CHARACTER_SECTIONS,+ editorFields: flattenSections(CHARACTER_SECTIONS),},{id: 'place',@@ -52,12 +181,8 @@ export const CATALOG_TYPES = Object.freeze([primaryContentKey: 'description',primaryContentLabel: 'Description',snippetFallbackKeys: ['description', 'summary', 'significance', 'notes'],- editorFields: [- ['slugline', 'Slugline', 'text'],- ['era', 'Era', 'text'],- ['description', 'Description', 'textarea'],- ['notes', 'Notes', 'textarea'],- ],+ editorSections: PLACE_SECTIONS,+ editorFields: flattenSections(PLACE_SECTIONS),},{id: 'object',@@ -66,11 +191,8 @@ export const CATALOG_TYPES = Object.freeze([primaryContentKey: 'description',primaryContentLabel: 'Description',snippetFallbackKeys: ['description', 'significance', 'summary', 'notes'],- editorFields: [- ['description', 'Description', 'textarea'],- ['significance', 'Significance', 'textarea'],- ['notes', 'Notes', 'textarea'],- ],+ editorSections: OBJECT_SECTIONS,+ editorFields: flattenSections(OBJECT_SECTIONS),},{id: 'idea',diff --git a/client/src/lib/catalogTypes.test.js b/client/src/lib/catalogTypes.test.jsnew file mode 100644index 0000000000..377ce3f178--- /dev/null+++ b/client/src/lib/catalogTypes.test.js@@ -0,0 +1,69 @@+import { describe, it, expect } from 'vitest';+import {+ CATALOG_TYPES,+ getCatalogType,+ CHARACTER_LIST_FIELDS,+} from './catalogTypes.js';++describe('catalogTypes — character sheet sections', () => {+ it('character/place/object carry grouped editorSections; light types do not', () => {+ expect(getCatalogType('character').editorSections).toBeTruthy();+ expect(getCatalogType('place').editorSections).toBeTruthy();+ expect(getCatalogType('object').editorSections).toBeTruthy();+ for (const id of ['idea', 'scene', 'concept']) {+ expect(getCatalogType(id).editorSections).toBeFalsy();+ }+ });++ it('editorFields is the flattened union of editorSections for rich types', () => {+ for (const id of ['character', 'place', 'object']) {+ const t = getCatalogType(id);+ const flat = t.editorSections.flatMap((s) => s.fields).map(([k]) => k);+ const fromFields = t.editorFields.map(([k]) => k);+ expect(fromFields).toEqual(flat);+ }+ });++ it('every section field tuple is [key, label, kind] with a valid kind', () => {+ for (const id of ['character', 'place', 'object']) {+ for (const section of getCatalogType(id).editorSections) {+ expect(typeof section.title).toBe('string');+ expect(Array.isArray(section.fields)).toBe(true);+ for (const [key, label, kind] of section.fields) {+ expect(typeof key).toBe('string');+ expect(typeof label).toBe('string');+ expect(['text', 'textarea']).toContain(kind);+ }+ }+ }+ });++ it('character sheet exposes the enriched canon scalar fields', () => {+ const keys = getCatalogType('character').editorFields.map(([k]) => k);+ // A representative slice of the sanitizeCharacter scalar fields the sheet+ // must now expose — identity, appearance, personality, goals, relationships.+ for (const k of ['role', 'pronouns', 'age', 'coreTheme', 'physicalDescription',+ 'visualNotes', 'silhouetteNotes', 'personality', 'speechPattern',+ 'motivations', 'likes', 'dislikes', 'background', 'relationships', 'skills', 'notes']) {+ expect(keys).toContain(k);+ }+ });++ it('section field keys are unique within a type (no key edited twice)', () => {+ for (const id of ['character', 'place', 'object']) {+ const keys = getCatalogType(id).editorFields.map(([k]) => k);+ expect(new Set(keys).size).toBe(keys.length);+ }+ });++ it('CHARACTER_LIST_FIELDS describes read-only canon arrays with renderer kinds', () => {+ const byKey = Object.fromEntries(CHARACTER_LIST_FIELDS.map((f) => [f.key, f]));+ expect(byKey.colorPalette.kind).toBe('colorPalette');+ expect(byKey.stats.kind).toBe('kv');+ expect(byKey.aliases.kind).toBe('text');+ });++ it('CATALOG_TYPES stays frozen', () => {+ expect(Object.isFrozen(CATALOG_TYPES)).toBe(true);+ });+});diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex d4fe843875..5603c85b91 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -7,7 +7,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import { useNavigate, useParams, Link } from 'react-router-dom';-import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star } from 'lucide-react';+import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star, ChevronDown } from 'lucide-react';import toast from '../components/ui/Toast';import {getCatalogIngredient,@@ -28,7 +28,7 @@ import { listImageGallery } from '../services/apiImageVideo';import IngredientPicker from '../components/IngredientPicker';import MediaImage from '../components/MediaImage';import TagPicker from '../components/TagPicker';-import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';+import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind, CHARACTER_LIST_FIELDS } from '../lib/catalogTypes';import { timeAgo } from '../utils/formatters';// Per-type editor field list + badge color now come from the shared registry@@ -275,7 +275,12 @@ export default function CatalogIngredient() {);}- const fields = getCatalogType(record.type)?.editorFields || getCatalogType('idea').editorFields;+ const typeDef = getCatalogType(record.type) || getCatalogType('idea');+ const fields = typeDef.editorFields || getCatalogType('idea').editorFields;+ // Grouped "character sheet" sections for the rich canon types+ // (character/place/object); light types (idea/scene/concept) have none and+ // fall back to the flat field list below.+ const sections = typeDef.editorSections || null;const badgeClass = CATALOG_BADGE_BY_ID[record.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';// Group refs by kind for the "Appears in" panel. Tolerates either an array@@ -287,6 +292,12 @@ export default function CatalogIngredient() {return acc;}, {});+ // First universe this ingredient belongs to — drives the "render reference+ // sheet" deep-link (the renderer needs the universe's full style data, which+ // lives on the Universe Builder surface). null when the ingredient isn't a+ // canon entry of any universe.+ const universeRef = (refsByKind.universe || [])[0] || null;+return (<section className="h-full overflow-y-auto p-4 md:p-6"><div className="max-w-4xl mx-auto space-y-5">@@ -348,21 +359,28 @@ export default function CatalogIngredient() {<TagPicker id="ingredient-tags" value={tags} onChange={setTags}placeholder="mentor, antagonist, season-1" /></div>- {fields.map(([key, label, kind]) => {- const inputId = `ingredient-${key}`;- const value = payload[key] ?? '';- const shared = `w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent`;- return (- <div key={key}>- <label htmlFor={inputId} className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</label>- {kind === 'textarea'- ? <textarea id={inputId} rows={3} value={value} onChange={(e) => updatePayload(key, e.target.value)} className={shared} />- : <input id={inputId} type="text" value={value} onChange={(e) => updatePayload(key, e.target.value)} className={shared} />}- </div>- );- })}+ {sections+ ? sections.map((section) => (+ <SheetSection key={section.title} title={section.title}+ fields={section.fields} payload={payload} onChange={updatePayload} />+ ))+ : fields.map(([key, label, kind]) => (+ <SheetField key={key} fieldKey={key} label={label} kind={kind}+ value={payload[key] ?? ''} onChange={updatePayload} />+ ))}++ {/* Read-only canon arrays (color palette, stats, aliases) — edited on+ the Universe Builder surface; surfaced here so the enriched canon+ is visible without leaving the page. */}+ {record.type === 'character' && (+ <CanonListFields payload={payload} fields={CHARACTER_LIST_FIELDS} />+ )}</div>+ {record.type === 'character' && (+ <ReferenceSheetPanel payload={payload} universeRef={universeRef} ingredientId={record.id} />+ )}+<div className="grid grid-cols-1 md:grid-cols-2 gap-4"><SourcesPanel sources={record.sources} /><RefsPanel refsByKind={refsByKind} />@@ -394,6 +412,162 @@ export default function CatalogIngredient() {);}+// One editable scalar field in the character sheet. `kind` is 'text' (single+// line) or 'textarea' (multi-line). Edits write straight through to the shared+// payload via `onChange(key, value)` — the same durable catalog row the+// Universe Builder canon surface edits.+function SheetField({ fieldKey, label, kind, value, onChange }) {+ const inputId = `ingredient-${fieldKey}`;+ const shared = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent';+ return (+ <div>+ <label htmlFor={inputId} className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</label>+ {kind === 'textarea'+ ? <textarea id={inputId} rows={3} value={value} onChange={(e) => onChange(fieldKey, e.target.value)} className={shared} />+ : <input id={inputId} type="text" value={value} onChange={(e) => onChange(fieldKey, e.target.value)} className={shared} />}+ </div>+ );+}++// One collapsible "sheet section" — a labeled group of scalar fields. Open by+// default; collapsing keeps the long character sheet manageable above the fold.+function SheetSection({ title, fields, payload, onChange }) {+ const [open, setOpen] = useState(true);+ return (+ <div className="border border-port-border rounded-lg overflow-hidden">+ <button type="button" onClick={() => setOpen((o) => !o)} aria-expanded={open}+ className="w-full flex items-center justify-between px-3 py-2 bg-port-bg/60 hover:bg-port-bg text-left">+ <span className="text-xs font-semibold uppercase tracking-wider text-gray-300">{title}</span>+ <ChevronDown size={14} aria-hidden="true"+ className={`text-gray-500 transition-transform ${open ? '' : '-rotate-90'}`} />+ </button>+ {open && (+ <div className="p-3 space-y-3">+ {fields.map(([key, label, kind]) => (+ <SheetField key={key} fieldKey={key} label={label} kind={kind}+ value={payload[key] ?? ''} onChange={onChange} />+ ))}+ </div>+ )}+ </div>+ );+}++// Read-only canon array fields (color palette, stats, aliases). The structured+// per-item editors live on the Universe Builder surface; here they render as+// labeled chips / swatches / key-value rows so the enriched canon is visible+// without leaving the Catalog page. Empty fields are skipped entirely.+function CanonListFields({ payload, fields }) {+ const present = fields.filter((f) => Array.isArray(payload[f.key]) && payload[f.key].length > 0);+ if (present.length === 0) return null;+ return (+ <div className="space-y-3 pt-1">+ {present.map((f) => (+ <div key={f.key}>+ <div className="flex items-center gap-1.5 text-xs uppercase tracking-wider text-gray-500 mb-1.5">+ {f.label}+ <span className="text-[9px] text-gray-600 normal-case tracking-normal">(edit in Universe Builder)</span>+ </div>+ {f.kind === 'colorPalette' ? (+ <div className="flex flex-wrap gap-2">+ {payload[f.key].map((c, i) => (+ <span key={c?.hex ? `${c.hex}-${i}` : i}+ className="inline-flex items-center gap-1.5 text-xs px-2 py-1 rounded border border-port-border bg-port-bg text-gray-200">+ <span className="w-3.5 h-3.5 rounded-sm border border-black/40"+ style={{ backgroundColor: c?.hex || 'transparent' }} aria-hidden="true" />+ {c?.name || c?.hex || '(unnamed)'}+ </span>+ ))}+ </div>+ ) : f.kind === 'kv' ? (+ <ul className="grid grid-cols-2 sm:grid-cols-3 gap-1.5">+ {payload[f.key].map((s, i) => (+ <li key={s?.key ? `${s.key}-${i}` : i}+ className="text-xs px-2 py-1 rounded border border-port-border bg-port-bg flex items-center justify-between gap-2">+ <span className="text-gray-400 truncate">{s?.key || s?.label || '?'}</span>+ <span className="text-gray-200 font-medium">{s?.value ?? ''}</span>+ </li>+ ))}+ </ul>+ ) : (+ <div className="flex flex-wrap gap-1.5">+ {payload[f.key].map((v, i) => (+ <span key={`${v}-${i}`} className="text-xs px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-200">+ {String(v)}+ </span>+ ))}+ </div>+ )}+ </div>+ ))}+ </div>+ );+}++// "Reference sheet" panel — shows the rendered character turnaround sheet when+// one exists (payload.referenceSheetImageRef / referenceSheets[]), served from+// the /data/image-refs/ static prefix. When no sheet exists but the character+// belongs to a universe, surfaces a deep-link to render one on the Universe+// Builder surface, which carries the universe's full style data (styleNotes,+// influences, palette, render settings) the renderer needs. Rendering inline+// here would duplicate that heavy pipeline — the deep-link keeps one render+// path. The character anchor (`#char-<ingredientId>`) lets the universe page+// scroll to the matching entry.+function ReferenceSheetPanel({ payload, universeRef, ingredientId }) {+ const sheets = payload?.referenceSheets && typeof payload.referenceSheets === 'object'+ ? Object.entries(payload.referenceSheets).filter(([, v]) => typeof v === 'string' && v)+ : [];+ const legacy = typeof payload?.referenceSheetImageRef === 'string' ? payload.referenceSheetImageRef : '';+ // De-dup: the legacy 'standard' pointer often duplicates a referenceSheets entry.+ const variants = [+ ...(legacy ? [['standard', legacy]] : []),+ ...sheets.filter(([, v]) => v !== legacy),+ ];+ const hasSheet = variants.length > 0;++ const universePath = universeRef?.refId+ ? `/universes/${encodeURIComponent(universeRef.refId)}#char-${encodeURIComponent(ingredientId)}`+ : null;++ return (+ <section className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between gap-2 mb-3 flex-wrap">+ <h2 className="text-sm font-semibold text-white flex items-center gap-1.5">+ <ImageIcon size={14} aria-hidden="true" /> Reference sheet+ </h2>+ {universePath && (+ <Link to={universePath}+ className="inline-flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">+ <Sparkles size={12} aria-hidden="true" />+ {hasSheet ? 'Re-render in Universe Builder' : 'Render in Universe Builder'}+ <ExternalLink size={11} aria-hidden="true" />+ </Link>+ )}+ </div>+ {hasSheet ? (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {variants.map(([variant, filename]) => (+ <figure key={variant} className="rounded border border-port-border overflow-hidden bg-port-bg">+ <MediaImage src={`/data/image-refs/${filename}`} alt={`${variant} reference sheet`}+ className="w-full object-contain max-h-[420px]" />+ <figcaption className="text-[10px] uppercase tracking-wider text-gray-500 px-2 py-1 border-t border-port-border">+ {variant}+ </figcaption>+ </figure>+ ))}+ </div>+ ) : (+ <p className="text-xs text-gray-500">+ No reference sheet rendered yet.+ {universePath+ ? ' Render one from the linked universe (it carries the style data the renderer needs).'+ : ' Link this character to a universe to render a reference sheet from its style data.'}+ </p>+ )}+ </section>+ );+}+// "Relations" panel — ingredient↔ingredient edges. Outbound edges (this// ingredient → other) are user-editable here; inbound edges (other → this// ingredient) are read-only because the owning ingredient is the other end.diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsxnew file mode 100644index 0000000000..fdc73b2e48--- /dev/null+++ b/client/src/pages/CatalogIngredient.test.jsx@@ -0,0 +1,120 @@+/**+ * Render tests for the CatalogIngredient character-sheet editor.+ *+ * Locks the enriched-sheet behavior: grouped sections expose the canon scalar+ * fields, read-only canon arrays (color palette, stats) render, and the+ * reference-sheet panel shows an existing sheet / a render deep-link.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++// Stable navigate mock — returning a fresh vi.fn() per call would change the+// load effect's dependency identity every render and re-fire the fetch, which+// races the second test in this file into a stuck "loading" state.+const { navigateMock } = vi.hoisted(() => ({ navigateMock: () => {} }));+vi.mock('react-router-dom', async (io) => {+ const actual = await io();+ return { ...actual, useParams: () => ({ id: 'cat-chr-1', type: 'character' }), useNavigate: () => navigateMock };+});++const { CHAR_FIXTURE } = vi.hoisted(() => ({+ CHAR_FIXTURE: {+ id: 'cat-chr-1',+ type: 'character',+ name: 'Ada Lovelace',+ tags: ['mentor', 'My Cool Universe'],+ payload: {+ role: 'Mentor',+ pronouns: 'she/her',+ physicalDescription: 'Sharp eyes, ink-stained cuffs.',+ motivations: 'Decode the machine.',+ dislikes: 'Being underestimated.',+ colorPalette: [{ name: 'Brass', hex: '#b08d57' }],+ stats: [{ key: 'Logic', value: '9' }],+ aliases: ['The Countess'],+ },+ refs: [{ refKind: 'universe', refId: 'u-1', refName: 'My Cool Universe', role: 'canon-character' }],+ sources: [],+ },+}));++vi.mock('../services/apiCatalog', () => ({+ getCatalogIngredient: vi.fn(async () => CHAR_FIXTURE),+ updateCatalogIngredient: vi.fn(),+ deleteCatalogIngredient: vi.fn(),+ listCatalogIngredientRelations: vi.fn(async () => ({ outbound: [], inbound: [] })),+ linkCatalogIngredientRelation: vi.fn(),+ unlinkCatalogIngredientRelation: vi.fn(),+ listCatalogIngredientRevisions: vi.fn(async () => ({ items: [] })),+ restoreCatalogIngredientRevision: vi.fn(),+ listCatalogIngredientMedia: vi.fn(async () => []),+ listCatalogIngredientMissingMedia: vi.fn(async () => ({ missing: [] })),+ attachCatalogIngredientMedia: vi.fn(),+ setCatalogIngredientPortrait: vi.fn(),+ detachCatalogIngredientMedia: vi.fn(),+}));++vi.mock('../services/apiImageVideo', () => ({ listImageGallery: vi.fn(async () => []) }));+vi.mock('../components/IngredientPicker', () => ({ default: () => null }));+vi.mock('../components/MediaImage', () => ({ default: ({ src, alt }) => <img src={src} alt={alt} /> }));+vi.mock('../components/TagPicker', () => ({ default: () => <div data-testid="tag-picker" /> }));+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));++import CatalogIngredient from './CatalogIngredient';+import { getCatalogIngredient } from '../services/apiCatalog';++const renderPage = () => render(<MemoryRouter><CatalogIngredient /></MemoryRouter>);++beforeEach(() => {+ getCatalogIngredient.mockImplementation(async () => CHAR_FIXTURE);+});++describe('CatalogIngredient — character sheet', () => {+ it('renders grouped sheet sections with the enriched canon scalar fields', async () => {+ renderPage();+ await waitFor(() => expect(screen.getByDisplayValue('Sharp eyes, ink-stained cuffs.')).toBeTruthy());+ expect(screen.getByText('Identity')).toBeTruthy();+ expect(screen.getByText('Appearance')).toBeTruthy();+ expect(screen.getByText('Goals & Drives')).toBeTruthy();+ expect(screen.getByDisplayValue('she/her')).toBeTruthy();+ expect(screen.getByDisplayValue('Decode the machine.')).toBeTruthy();+ expect(screen.getByDisplayValue('Being underestimated.')).toBeTruthy();+ });++ it('renders read-only canon arrays (color palette + stats)', async () => {+ renderPage();+ await waitFor(() => expect(screen.getByText('Color Palette')).toBeTruthy());+ expect(screen.getByText('Brass')).toBeTruthy();+ expect(screen.getByText('Logic')).toBeTruthy();+ expect(screen.getByText('The Countess')).toBeTruthy();+ });++ it('shows a render-reference-sheet deep-link when none exists and a universe ref is present', async () => {+ renderPage();+ await waitFor(() => expect(screen.getByText(/Render in Universe Builder/i)).toBeTruthy());+ const link = screen.getByText(/Render in Universe Builder/i).closest('a');+ expect(link.getAttribute('href')).toContain('/universes/u-1');+ });++ it('shows an existing reference sheet image when payload carries one', async () => {+ getCatalogIngredient.mockImplementation(async () => ({+ ...CHAR_FIXTURE,+ payload: { ...CHAR_FIXTURE.payload, referenceSheetImageRef: 'sheet-123.png' },+ }));+ renderPage();+ await waitFor(() => {+ const img = screen.getByAltText('standard reference sheet');+ expect(img.getAttribute('src')).toBe('/data/image-refs/sheet-123.png');+ });+ expect(screen.getByText(/Re-render in Universe Builder/i)).toBeTruthy();+ });++ it('collapses a sheet section when its header is clicked', async () => {+ renderPage();+ await waitFor(() => expect(screen.getByDisplayValue('she/her')).toBeTruthy());+ fireEvent.click(screen.getByText('Identity'));+ await waitFor(() => expect(screen.queryByDisplayValue('she/her')).toBeNull());+ });+});diff --git a/scripts/migrations/053-catalog-friendly-universe-tags.js b/scripts/migrations/053-catalog-friendly-universe-tags.jsnew file mode 100644index 0000000000..b3e1dff259--- /dev/null+++ b/scripts/migrations/053-catalog-friendly-universe-tags.js@@ -0,0 +1,30 @@+/**+ * Registration stub for the friendly-universe-tag data repair.+ *+ * The original bible→catalog backfill stamped MACHINE tags onto every promoted+ * character/place/object — a literal `from-universe` marker plus a+ * `universe:<universeId>` id tag. Those are unreadable in the Catalog UI (a raw+ * UUID means nothing to a human) and leak an internal id into the tag taxonomy.+ * The structured universe link already lives durably in+ * `catalog_ingredient_refs`, so the repair rewrites the machine tags into the+ * friendly universe NAME tag while preserving every user-supplied tag.+ *+ * The actual repair walks every catalog ingredient and PATCHes its tags, so it+ * needs the Postgres pool — but the `scripts/migrations/` runner executes+ * BEFORE the pool is initialized (the same reason migrations 048–052 are+ * boot-time + stub-registered). The repair therefore runs at boot from+ * `server/scripts/repairUniverseTags.js` (after `ensureSchema()` + the bible→+ * catalog backfill), marker-gated in `data/catalog-universe-tags.applied.json`.+ *+ * This stub exists so the change is *registered the standard way*: it lands in+ * `data/migrations.applied.json` so the migration ledger and `git log` show+ * when the friendly-tag repair was introduced.+ *+ * No-op + idempotent: nothing to do in the file runner.+ */++export default {+ async up() {+ console.log('🏷️ friendly universe tags: repair runs at boot (repairUniverseTags.js); nothing to do in the file runner');+ },+};diff --git a/server/index.js b/server/index.jsindex 7f32c35113..b0362f0ba8 100644--- a/server/index.js+++ b/server/index.js@@ -692,6 +692,12 @@ ensureSelf()await ensureSchema();const { migrateBibleToCatalog } = await import('./scripts/migrateBibleToCatalog.js');await migrateBibleToCatalog();+ // One-time data repair: rewrite legacy machine universe tags+ // (`from-universe`, `universe:<id>`) on backfilled rows into the friendly+ // universe NAME tag. Runs after the backfill so promoted rows exist;+ // marker-gated in data/catalog-universe-tags.applied.json.+ const { repairUniverseTags } = await import('./scripts/repairUniverseTags.js');+ await repairUniverseTags();// Per-record catalog payload-shape migration — walks rows whose stored// payload.schemaVersion lags the registry-current and applies registered// upgraders. No-ops via marker once an install is at the high-waterdiff --git a/server/lib/README.md b/server/lib/README.mdindex 6680410696..214df1f995 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -52,6 +52,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `bibleExtractor.js` | LLM bible-extraction stage + sanitization. || `catalogBulkParsers.js` | Dependency-free markdown/CSV/JSON parsers for `POST /api/catalog/bulk-import` and YAML/markdown serializers for `GET /api/catalog/export`. || `catalogTypes.js` | Shared catalog ingredient TYPE REGISTRY — one entry per type drives validation enum, ID prefix, FTS field set, extraction shape, per-record `payloadSchemaVersion` + upgraders, per-type `defaultTags`. Also exports the relation-kind registry and the tag-taxonomy helpers (`canonicalTagKey`, `tagIdForKey`, `defaultTagsForType`). Mirrored on the client at `client/src/lib/catalogTypes.js`. |+| `catalogUniverseTags.js` | Pure transform that rewrites legacy machine universe tags (`from-universe`, `universe:<id>`) on backfilled catalog ingredients into friendly universe-NAME tags, preserving user tags + the structured `catalog_ingredient_refs` link. Used by the boot-time repair and the bible→catalog backfill. || `comicScriptParser.js` | Marvel/DC-format comic script parser. || `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. || `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |diff --git a/server/lib/catalogUniverseTags.js b/server/lib/catalogUniverseTags.jsnew file mode 100644index 0000000000..762e978209--- /dev/null+++ b/server/lib/catalogUniverseTags.js@@ -0,0 +1,115 @@+/**+ * Friendly universe-tag transforms for catalog ingredients backfilled from+ * universe canon.+ *+ * The original bible→catalog backfill stamped MACHINE tags onto every promoted+ * character/place/object: a literal `from-universe` marker plus a+ * `universe:<universeId>` id tag. Those are unreadable in the Catalog UI (a raw+ * UUID is meaningless to a human) and they leak an internal id into the tag+ * taxonomy. The structured universe link is already durable in+ * `catalog_ingredient_refs` (refKind `universe`, role `canon-<kind>`), so the+ * tag does NOT need to carry the id for querying — the ref table owns that.+ *+ * These pure helpers replace the machine tags with the friendly universe NAME+ * tag (e.g. "My Cool Universe") while preserving every user-supplied tag. They+ * are used by:+ * - the boot-time data repair (`server/scripts/repairUniverseTags.js`) that+ * rewrites existing rows once per install, and+ * - the bible→catalog backfill (`server/scripts/migrateBibleToCatalog.js`)+ * so NEW promotions stamp the friendly tag from the start.+ *+ * Pure + dependency-free so they unit-test without a DB.+ */++// The legacy machine marker tag (no id).+export const LEGACY_UNIVERSE_MARKER_TAG = 'from-universe';++// Prefix of the legacy id-carrying tag (`universe:<universeId>`).+export const LEGACY_UNIVERSE_ID_TAG_PREFIX = 'universe:';++/**+ * True when `tag` is one of the legacy machine universe tags+ * (`from-universe` or `universe:<id>`). Case-insensitive on the marker; the+ * id-tag match is prefix-based so any `universe:<anything>` is caught.+ */+export function isLegacyUniverseTag(tag) {+ if (typeof tag !== 'string') return false;+ const t = tag.trim().toLowerCase();+ if (t === LEGACY_UNIVERSE_MARKER_TAG) return true;+ return t.startsWith(LEGACY_UNIVERSE_ID_TAG_PREFIX);+}++/**+ * Extract the universe id from a legacy `universe:<id>` tag, or null when the+ * tag isn't an id tag. The marker tag (`from-universe`) returns null — it+ * carries no id.+ */+export function universeIdFromLegacyTag(tag) {+ if (typeof tag !== 'string') return null;+ const t = tag.trim();+ if (!t.toLowerCase().startsWith(LEGACY_UNIVERSE_ID_TAG_PREFIX)) return null;+ const id = t.slice(LEGACY_UNIVERSE_ID_TAG_PREFIX.length).trim();+ return id || null;+}++/**+ * Compute the friendly tag set for an ingredient's tags.+ *+ * - Strips every legacy machine universe tag (`from-universe`, `universe:<id>`).+ * - For each distinct universe id found in those legacy id tags, appends the+ * friendly universe NAME (resolved via `nameForId(id)`) when one resolves.+ * - Preserves every other (user-supplied) tag, in order, de-duplicated by+ * `canonicalKey` against both the kept tags AND the names just added (so+ * "My Universe" and "my universe" don't both appear).+ * - When a universe id can't be resolved to a name (deleted universe, missing+ * lookup), the id tag is still dropped but no name is added — the structured+ * ref remains the source of truth, and re-running the repair after the+ * universe re-syncs picks the name up.+ *+ * Returns `{ tags, changed }`. `changed` is false when nothing was rewritten,+ * so callers can skip a no-op DB write.+ *+ * @param {string[]} tags existing ingredient tags+ * @param {(id:string)=>string|null|undefined} nameForId universe id → name+ * @param {(label:string)=>string} canonicalKey tag dedup key fn+ */+export function friendlifyUniverseTags(tags, nameForId, canonicalKey) {+ const input = Array.isArray(tags) ? tags : [];+ const kept = [];+ const universeIds = [];+ let sawLegacy = false;++ for (const tag of input) {+ if (isLegacyUniverseTag(tag)) {+ sawLegacy = true;+ const id = universeIdFromLegacyTag(tag);+ if (id && !universeIds.includes(id)) universeIds.push(id);+ continue;+ }+ kept.push(tag);+ }++ // Resolve names for every distinct universe id; skip unresolved ones.+ const names = [];+ for (const id of universeIds) {+ const name = nameForId(id);+ if (typeof name === 'string' && name.trim()) names.push(name.trim());+ }++ // De-dup the friendly names against kept tags + each other.+ const seen = new Set(kept.map((t) => canonicalKey(t)));+ const addedNames = [];+ for (const name of names) {+ const key = canonicalKey(name);+ if (!key || seen.has(key)) continue;+ seen.add(key);+ addedNames.push(name);+ }++ const result = [...kept, ...addedNames];+ // `changed` when we stripped any legacy tag OR added any friendly name.+ // (A row could carry `universe:<id>` whose name dedups against an existing+ // user tag — still changed, because the machine tag was removed.)+ const changed = sawLegacy || addedNames.length > 0;+ return { tags: result, changed };+}diff --git a/server/lib/catalogUniverseTags.test.js b/server/lib/catalogUniverseTags.test.jsnew file mode 100644index 0000000000..25cb58fc2e--- /dev/null+++ b/server/lib/catalogUniverseTags.test.js@@ -0,0 +1,102 @@+import { describe, it, expect } from 'vitest';+import {+ isLegacyUniverseTag,+ universeIdFromLegacyTag,+ friendlifyUniverseTags,+} from './catalogUniverseTags.js';++// Match the canonical tag key used by catalogTypes.canonicalTagKey so the+// dedup behavior under test mirrors production.+const canonicalKey = (s) => (typeof s === 'string' ? s.trim().replace(/\s+/g, ' ').toLowerCase() : '');++describe('catalogUniverseTags — legacy tag detection', () => {+ it('recognizes the marker tag case-insensitively', () => {+ expect(isLegacyUniverseTag('from-universe')).toBe(true);+ expect(isLegacyUniverseTag('From-Universe')).toBe(true);+ expect(isLegacyUniverseTag(' from-universe ')).toBe(true);+ });++ it('recognizes id tags by prefix', () => {+ expect(isLegacyUniverseTag('universe:14590a09-5a49-4994-b401-395ee354528d')).toBe(true);+ expect(isLegacyUniverseTag('Universe:abc')).toBe(true);+ });++ it('leaves user tags alone', () => {+ expect(isLegacyUniverseTag('mentor')).toBe(false);+ expect(isLegacyUniverseTag('season-1')).toBe(false);+ expect(isLegacyUniverseTag('multiverse')).toBe(false); // not the prefix `universe:`+ expect(isLegacyUniverseTag(42)).toBe(false);+ });++ it('extracts the universe id from an id tag', () => {+ expect(universeIdFromLegacyTag('universe:u-123')).toBe('u-123');+ expect(universeIdFromLegacyTag('Universe: u-123 ')).toBe('u-123');+ expect(universeIdFromLegacyTag('universe:')).toBeNull();+ expect(universeIdFromLegacyTag('from-universe')).toBeNull();+ expect(universeIdFromLegacyTag('mentor')).toBeNull();+ });+});++describe('catalogUniverseTags — friendlifyUniverseTags', () => {+ const nameFor = (id) => ({ 'u-1': 'My Cool Universe', 'u-2': 'Neon City' }[id] || null);++ it('replaces machine tags with the friendly universe name, preserving user tags', () => {+ const { tags, changed } = friendlifyUniverseTags(+ ['mentor', 'from-universe', 'universe:u-1', 'season-1'],+ nameFor,+ canonicalKey,+ );+ expect(changed).toBe(true);+ expect(tags).toEqual(['mentor', 'season-1', 'My Cool Universe']);+ // No machine tags survive.+ expect(tags.some((t) => isLegacyUniverseTag(t))).toBe(false);+ });++ it('is a no-op when there are no legacy tags', () => {+ const { tags, changed } = friendlifyUniverseTags(['hero', 'noir'], nameFor, canonicalKey);+ expect(changed).toBe(false);+ expect(tags).toEqual(['hero', 'noir']);+ });++ it('drops an unresolved universe id tag but adds no name (and still reports changed)', () => {+ const { tags, changed } = friendlifyUniverseTags(+ ['hero', 'universe:u-deleted', 'from-universe'],+ nameFor,+ canonicalKey,+ );+ expect(changed).toBe(true);+ expect(tags).toEqual(['hero']);+ });++ it('dedupes the friendly name against an existing user tag (case-insensitive)', () => {+ const { tags, changed } = friendlifyUniverseTags(+ ['my cool universe', 'universe:u-1', 'from-universe'],+ nameFor,+ canonicalKey,+ );+ // changed because machine tags were stripped, even though no new name added.+ expect(changed).toBe(true);+ expect(tags).toEqual(['my cool universe']);+ });++ it('handles multiple distinct universe ids', () => {+ const { tags } = friendlifyUniverseTags(+ ['universe:u-1', 'universe:u-2', 'from-universe'],+ nameFor,+ canonicalKey,+ );+ expect(tags).toEqual(['My Cool Universe', 'Neon City']);+ });++ it('is idempotent — a second pass over the friendlified set is a no-op', () => {+ const first = friendlifyUniverseTags(['mentor', 'universe:u-1', 'from-universe'], nameFor, canonicalKey);+ const second = friendlifyUniverseTags(first.tags, nameFor, canonicalKey);+ expect(second.changed).toBe(false);+ expect(second.tags).toEqual(first.tags);+ });++ it('tolerates non-array input', () => {+ expect(friendlifyUniverseTags(null, nameFor, canonicalKey)).toEqual({ tags: [], changed: false });+ expect(friendlifyUniverseTags(undefined, nameFor, canonicalKey)).toEqual({ tags: [], changed: false });+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 1422693597..00f9afc928 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -34,6 +34,7 @@ export * from './validation.js';export * from './bibleExtractor.js';export * as catalogBulkParsers from './catalogBulkParsers.js';export * from './catalogTypes.js';+export * as catalogUniverseTags from './catalogUniverseTags.js';export * from './canonPrompt.js';export * from './comicScriptParser.js';export * from './composeStyledPrompt.js';diff --git a/server/scripts/migrateBibleToCatalog.js b/server/scripts/migrateBibleToCatalog.jsindex 7543272ac3..1c82db923d 100644--- a/server/scripts/migrateBibleToCatalog.js+++ b/server/scripts/migrateBibleToCatalog.js@@ -93,7 +93,7 @@ async function writeMarker(payload) {* a pre-deterministic build) → recreate locally with the explicit foreign* id so cross-peer identity holds, until the network re-converges.*/-async function promoteEntry({ universeId, entry, kind, role }) {+async function promoteEntry({ universeId, universeName, entry, kind, role }) {if (!entry?.name || !entry?.id) return { skipped: true, reason: 'missing-id-or-name' };const payload = { ...entry };@@ -102,11 +102,17 @@ async function promoteEntry({ universeId, entry, kind, role }) {delete payload.createdAt;delete payload.updatedAt;- // Audit tags first so a `.slice(-N)` preserves them on overflow rather than- // dropping them; user-supplied tags accept being trimmed before audit tags.- const auditTags = ['from-universe', `universe:${universeId}`];+ // Friendly universe-name tag (e.g. "My Cool Universe") instead of the legacy+ // machine tags (`from-universe` + `universe:<uuid>`) — the structured link+ // already lives durably in catalog_ingredient_refs (refKind universe, role+ // canon-<kind>), so the tag is purely a human-readable affordance and never+ // needs the id. Existing rows with the old machine tags are repaired+ // separately by server/scripts/repairUniverseTags.js. Audit/system tags go+ // last so a `.slice(-N)` overflow preserves them over trimmed user tags.+ const friendlyName = typeof universeName === 'string' ? universeName.trim() : '';+ const systemTags = friendlyName ? [friendlyName] : [];const userTags = Array.isArray(entry.tags) ? entry.tags : [];- const tags = [...userTags, ...auditTags].slice(-12);+ const tags = [...userTags, ...systemTags].slice(-12);const targetId = entry.ingredientId || deterministicIngredientId(universeId, kind, entry.id);@@ -161,7 +167,7 @@ async function migrateUniverse(universe) {for (const entry of list) {if (!entry?.id) continue;try {- const result = await promoteEntry({ universeId: universe.id, entry, kind, role });+ const result = await promoteEntry({ universeId: universe.id, universeName: universe.name, entry, kind, role });if (result.peerReconciled) {stats.peerReconciled++;continue;diff --git a/server/scripts/repairUniverseTags.js b/server/scripts/repairUniverseTags.jsnew file mode 100644index 0000000000..9b89a73958--- /dev/null+++ b/server/scripts/repairUniverseTags.js@@ -0,0 +1,122 @@+/**+ * One-time data repair: friendlify legacy machine universe tags on catalog+ * ingredients.+ *+ * The original bible→catalog backfill stamped `from-universe` ++ * `universe:<universeId>` machine tags onto every promoted character/place/+ * object. Those are unreadable in the Catalog UI (a raw UUID means nothing to a+ * human) and leak an internal id into the tag taxonomy. This repair rewrites+ * them into the friendly universe NAME tag (e.g. "My Cool Universe") while+ * preserving every user-supplied tag — the structured universe link already+ * lives durably in `catalog_ingredient_refs`, so the tag never needed the id+ * for querying.+ *+ * Idempotent: the transform (`friendlifyUniverseTags`) only rewrites rows that+ * still carry a legacy machine tag, so a second pass over an already-repaired+ * row is a no-op. A marker in `data/catalog-universe-tags.applied.json` gates+ * the walk so it doesn't re-query every ingredient on every boot once done.+ *+ * Wired into server/index.js at boot, after `ensureSchema()` + the bible→+ * catalog backfill, so promoted rows exist before this runs.+ *+ * The corresponding `scripts/migrations/053-catalog-friendly-universe-tags.js`+ * is a registration stub for the migration ledger — the actual repair runs+ * here (boot-time) because the `scripts/migrations/` runner executes before the+ * DB pool is up, the same reason migrations 048–052 are boot-time + stubbed.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS } from '../lib/fileUtils.js';+import { friendlifyUniverseTags } from '../lib/catalogUniverseTags.js';+import { canonicalTagKey } from '../lib/catalogTypes.js';+import { listUniverses } from '../services/universeBuilder.js';+import * as catalogDB from '../services/catalogDB.js';++const MARKER_VERSION = 1;+const MARKER_FILENAME = 'catalog-universe-tags.applied.json';++async function readMarker() {+ const path = join(PATHS.data, MARKER_FILENAME);+ const raw = await readFile(path, 'utf-8').catch(() => null);+ if (!raw) return null;+ try { return JSON.parse(raw); } catch { return null; }+}++async function writeMarker(payload) {+ const path = join(PATHS.data, MARKER_FILENAME);+ await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');+}++/**+ * Build a universeId → name lookup from every universe (including deleted, so a+ * row tagged with a soft-deleted universe still resolves to a readable name+ * rather than getting its name dropped).+ */+async function buildUniverseNameMap() {+ const universes = await listUniverses({ includeDeleted: true });+ const map = new Map();+ for (const u of universes) {+ if (u?.id && typeof u.name === 'string' && u.name.trim()) {+ map.set(u.id, u.name.trim());+ }+ }+ return map;+}++/**+ * Public entry point. Runs once, then no-ops on every subsequent boot via the+ * marker file. `force` re-runs the walk (used by tests / an admin re-trigger).+ */+export async function repairUniverseTags({ force = false } = {}) {+ const marker = await readMarker();+ if (marker?.version === MARKER_VERSION && !force) {+ return { skipped: true, marker };+ }++ console.log('🏷️ universe-tag repair: starting');+ const nameMap = await buildUniverseNameMap();+ const nameForId = (id) => nameMap.get(id) || null;++ const totals = { scanned: 0, rewritten: 0, errors: 0 };+ // Page through every ingredient. Only character/place/object rows can carry+ // the legacy tags, but a tag-only scan is cheap and future-proof, so we walk+ // all rows and let the pure transform decide what's a no-op.+ const PAGE = 200;+ let offset = 0;+ for (;;) {+ const rows = await catalogDB.listIngredients({ limit: PAGE, offset });+ if (!Array.isArray(rows) || rows.length === 0) break;+ for (const ing of rows) {+ totals.scanned++;+ const { tags, changed } = friendlifyUniverseTags(ing.tags, nameForId, canonicalTagKey);+ if (!changed) continue;+ try {+ // `source: 'sync'` keeps the rewrite out of the user-facing revision+ // diff noise — it's a system data repair, not a user edit. (Tag changes+ // still record a revision; the badge just reads as a sync rewrite.)+ await catalogDB.updateIngredient(ing.id, { tags }, { source: 'sync', actor: 'universe-tag-repair' });+ totals.rewritten++;+ } catch (err) {+ console.error(`🏷️ universe-tag repair failed (${ing.id}): ${err.message}`);+ totals.errors++;+ }+ }+ if (rows.length < PAGE) break;+ offset += PAGE;+ }++ const payload = {+ version: MARKER_VERSION,+ completedAt: new Date().toISOString(),+ stats: totals,+ };+ await writeMarker(payload);++ console.log(+ `🏷️ universe-tag repair: ${totals.scanned} scanned, ` ++ `${totals.rewritten} rewritten, ${totals.errors} errors`,+ );++ return { skipped: false, ...payload };+}diff --git a/server/scripts/repairUniverseTags.test.js b/server/scripts/repairUniverseTags.test.jsnew file mode 100644index 0000000000..0825b0685b--- /dev/null+++ b/server/scripts/repairUniverseTags.test.js@@ -0,0 +1,111 @@+/**+ * Tests for the boot-time friendly-universe-tag repair.+ *+ * catalogDB + universeBuilder + the marker file are mocked, so this exercises+ * the walk/rewrite orchestration (the pure transform is unit-tested in+ * server/lib/catalogUniverseTags.test.js):+ * - rewrites rows carrying legacy machine tags to the friendly name;+ * - leaves clean rows untouched (no PATCH);+ * - paginates through more than one page;+ * - marker high-water skip on an already-repaired install.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const fsState = { marker: null, written: null };+const dbState = { ingredients: [], updates: [] };++vi.mock('fs/promises', () => ({+ readFile: vi.fn(async () => (fsState.marker == null+ ? Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))+ : JSON.stringify(fsState.marker))),+ writeFile: vi.fn(async (_p, data) => { fsState.written = JSON.parse(data); }),+}));++vi.mock('../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-data' } }));++vi.mock('../services/universeBuilder.js', () => ({+ listUniverses: vi.fn(async () => [+ { id: 'u-1', name: 'My Cool Universe' },+ { id: 'u-2', name: 'Neon City' },+ ]),+}));++vi.mock('../services/catalogDB.js', () => ({+ listIngredients: vi.fn(async ({ limit, offset }) => dbState.ingredients.slice(offset, offset + limit)),+ updateIngredient: vi.fn(async (id, patch, ctx) => {+ dbState.updates.push({ id, patch, ctx });+ const row = dbState.ingredients.find((r) => r.id === id);+ if (row) row.tags = patch.tags;+ return row;+ }),+}));++const { repairUniverseTags } = await import('./repairUniverseTags.js');++beforeEach(() => {+ fsState.marker = null;+ fsState.written = null;+ dbState.ingredients = [];+ dbState.updates = [];+});++describe('repairUniverseTags', () => {+ it('rewrites machine tags to the friendly universe name and leaves clean rows alone', async () => {+ dbState.ingredients = [+ { id: 'cat-chr-1', tags: ['mentor', 'from-universe', 'universe:u-1'] },+ { id: 'cat-plc-2', tags: ['from-universe', 'universe:u-2', 'noir'] },+ { id: 'cat-idea-3', tags: ['standalone-idea'] }, // no legacy tags+ ];++ const result = await repairUniverseTags();++ expect(result.skipped).toBe(false);+ expect(result.stats.scanned).toBe(3);+ expect(result.stats.rewritten).toBe(2);+ expect(dbState.updates).toHaveLength(2);++ const byId = Object.fromEntries(dbState.updates.map((u) => [u.id, u.patch.tags]));+ expect(byId['cat-chr-1']).toEqual(['mentor', 'My Cool Universe']);+ expect(byId['cat-plc-2']).toEqual(['noir', 'Neon City']);+ // The clean idea row was never PATCHed.+ expect(dbState.updates.some((u) => u.id === 'cat-idea-3')).toBe(false);+ // Repair edits are tagged as a system 'sync' source, not a user edit.+ expect(dbState.updates[0].ctx.source).toBe('sync');+ // Marker written for idempotent skip next boot.+ expect(fsState.written.version).toBe(1);+ });++ it('skips entirely when the marker is already at the current version', async () => {+ fsState.marker = { version: 1, completedAt: '2026-01-01T00:00:00Z' };+ dbState.ingredients = [{ id: 'cat-chr-1', tags: ['from-universe', 'universe:u-1'] }];++ const result = await repairUniverseTags();++ expect(result.skipped).toBe(true);+ expect(dbState.updates).toHaveLength(0);+ });++ it('re-runs the walk when forced even with a marker present', async () => {+ fsState.marker = { version: 1 };+ dbState.ingredients = [{ id: 'cat-chr-1', tags: ['from-universe', 'universe:u-1'] }];++ const result = await repairUniverseTags({ force: true });++ expect(result.skipped).toBe(false);+ expect(dbState.updates).toHaveLength(1);+ });++ it('paginates through more than one page', async () => {+ // 250 rows, each carrying a legacy tag — page size is 200, so two pages.+ dbState.ingredients = Array.from({ length: 250 }, (_, i) => ({+ id: `cat-chr-${i}`,+ tags: ['from-universe', 'universe:u-1'],+ }));++ const result = await repairUniverseTags();++ expect(result.stats.scanned).toBe(250);+ expect(result.stats.rewritten).toBe(250);+ });+});