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
promote catalog tags to a first-class catalog_tags table with autocomplete
[._.]/ Adam Eivyf333c6e0090c
diff --git a/client/src/components/QuickIdeaCapture.jsx b/client/src/components/QuickIdeaCapture.jsxindex 0e573f67b5..96c8e586e3 100644--- a/client/src/components/QuickIdeaCapture.jsx+++ b/client/src/components/QuickIdeaCapture.jsx@@ -15,32 +15,24 @@ import { useState, useRef, useMemo } from 'react';import { Link } from 'react-router-dom';import { Send } from 'lucide-react';import toast from './ui/Toast';+import TagPicker from './TagPicker';import { createCatalogIngredient } from '../services/apiCatalog';import { CATALOG_TYPES, getCatalogType } from '../lib/catalogTypes';const TYPES = CATALOG_TYPES;-// Splits a comma-or-space-separated tag string into a clean array. Per-tag-// length is capped at TAG_MAX_CHARS (mirrors the server's BIBLE_LIMITS.TAG_MAX-// used by catalogIngredientCreateSchema) so a 60+ char paste doesn't 400 the-// fast-capture submit. Tag count is capped at TAGS_MAX (mirrors-// BIBLE_LIMITS.TAGS_PER_ENTRY_MAX).+// Per-tag length cap (mirrors BIBLE_LIMITS.TAG_MAX used by+// catalogIngredientCreateSchema) + tag-count cap (mirrors+// BIBLE_LIMITS.TAGS_PER_ENTRY_MAX). The server still re-validates + normalizes;+// these keep the fast-capture submit from 400-ing on an oversized tag.const TAG_MAX_CHARS = 60;const TAGS_MAX = 12;-function parseTags(raw) {- if (!raw) return [];- return raw- .split(/[,\s]+/)- .map((t) => t.trim().slice(0, TAG_MAX_CHARS))- .filter(Boolean)- .slice(0, TAGS_MAX);-}export default function QuickIdeaCapture() {const [type, setType] = useState('idea');const [name, setName] = useState('');const [content, setContent] = useState('');- const [tagsRaw, setTagsRaw] = useState('');+ const [tags, setTags] = useState([]);const [isSubmitting, setIsSubmitting] = useState(false);const submittingRef = useRef(false);@@ -60,7 +52,6 @@ export default function QuickIdeaCapture() {const payload = {};const trimmedContent = content.trim();if (trimmedContent) payload[contentKey] = trimmedContent;- const tags = parseTags(tagsRaw);// silent: own error UI below — avoids double-toast through the request helper.const created = await createCatalogIngredient(@@ -79,7 +70,7 @@ export default function QuickIdeaCapture() {// Optimistic clear so the user can keep capturing rapid-fire.setName('');setContent('');- setTagsRaw('');+ setTags([]);// Toast with an "Open" link to the freshly-created ingredient detail.toast.success(@@ -141,16 +132,18 @@ export default function QuickIdeaCapture() {className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:outline-none focus:border-port-accent resize-none"/>- <div className="flex gap-2 items-center">- <label htmlFor="quick-idea-tags" className="sr-only">Tags</label>- <input- id="quick-idea-tags"- type="text"- placeholder="Tags (comma or space separated)"- value={tagsRaw}- onChange={(e) => setTagsRaw(e.target.value)}- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-xs focus:outline-none focus:border-port-accent"- />+ <div className="flex gap-2 items-start">+ <div className="flex-1">+ <label htmlFor="quick-idea-tags" className="sr-only">Tags</label>+ <TagPicker+ id="quick-idea-tags"+ value={tags}+ onChange={setTags}+ placeholder="Tags…"+ maxTags={TAGS_MAX}+ maxTagChars={TAG_MAX_CHARS}+ />+ </div><buttontype="submit"disabled={!name.trim() || isSubmitting}diff --git a/client/src/components/TagPicker.jsx b/client/src/components/TagPicker.jsxnew file mode 100644index 0000000000..faf3c31648--- /dev/null+++ b/client/src/components/TagPicker.jsx@@ -0,0 +1,143 @@+/**+ * TagPicker — chip-list tag editor with canonical-tag autocomplete.+ *+ * Backs the tag fields on CatalogIngredient.jsx + the Quick Idea widget. The+ * selected tags render as removable chips; typing queries the canonical+ * `catalog_tags` table (`GET /api/catalog/tags?q=`, debounced) and shows a+ * suggestion dropdown. Enter / comma / picking a suggestion commits the current+ * input as a tag. Freeform tags are allowed (the server normalizes + creates a+ * canonical row on save), so this is autocomplete-assisted, not a closed list.+ *+ * Controlled: `value` is the array of tag labels; `onChange(nextArray)` fires+ * on every add/remove. Client-side dedup uses `canonicalTagKey` so `Noir` and+ * `noir` don't both show as chips before save (matching the server's dedup).+ */++import { useEffect, useRef, useState } from 'react';+import { X } from 'lucide-react';+import { listCatalogTags } from '../services/apiCatalog';+import { canonicalTagKey } from '../lib/catalogTypes';++export default function TagPicker({+ value = [],+ onChange,+ id = 'tag-picker',+ placeholder = 'Add a tag…',+ maxTags = 12,+ maxTagChars = 60,+}) {+ const [input, setInput] = useState('');+ const [suggestions, setSuggestions] = useState([]);+ const [open, setOpen] = useState(false);+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);++ // Debounced autocomplete fetch. A stale generation counter prevents an+ // earlier-but-slower response from clobbering a later one's results.+ const genRef = useRef(0);+ useEffect(() => {+ const term = input.trim();+ if (!term) { setSuggestions([]); return undefined; }+ const gen = ++genRef.current;+ const timer = setTimeout(() => {+ listCatalogTags({ q: term, limit: 8, silent: true })+ .then((res) => {+ if (!mountedRef.current || gen !== genRef.current) return;+ setSuggestions(Array.isArray(res?.items) ? res.items : []);+ })+ .catch(() => { if (mountedRef.current && gen === genRef.current) setSuggestions([]); });+ }, 200);+ return () => clearTimeout(timer);+ }, [input]);++ const selectedKeys = new Set(value.map(canonicalTagKey));++ const addTag = (raw) => {+ const label = String(raw || '').trim().replace(/\s+/g, ' ').slice(0, maxTagChars);+ const key = canonicalTagKey(label);+ if (!key) return;+ if (selectedKeys.has(key)) { setInput(''); return; }+ if (value.length >= maxTags) return;+ onChange?.([...value, label]);+ setInput('');+ setSuggestions([]);+ };++ const removeTag = (label) => {+ const key = canonicalTagKey(label);+ onChange?.(value.filter((t) => canonicalTagKey(t) !== key));+ };++ const handleKeyDown = (e) => {+ if (e.key === 'Enter' || e.key === ',') {+ e.preventDefault();+ if (input.trim()) addTag(input);+ } else if (e.key === 'Backspace' && !input && value.length > 0) {+ // Backspace on an empty input pops the last chip (common chip-input UX).+ removeTag(value[value.length - 1]);+ }+ };++ // Suggestions not already selected.+ const visibleSuggestions = suggestions.filter((s) => !selectedKeys.has(canonicalTagKey(s.label)));++ return (+ <div className="relative">+ <div className="flex flex-wrap items-center gap-1.5 px-2 py-1.5 bg-port-bg border border-port-border rounded focus-within:border-port-accent">+ {value.map((label) => (+ <span+ key={label}+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-port-accent/15 text-port-accent text-xs"+ >+ {label}+ <button+ type="button"+ onClick={() => removeTag(label)}+ className="hover:text-white"+ aria-label={`Remove tag ${label}`}+ >+ <X size={12} />+ </button>+ </span>+ ))}+ <input+ id={id}+ type="text"+ value={input}+ onChange={(e) => { setInput(e.target.value); setOpen(true); }}+ onKeyDown={handleKeyDown}+ onFocus={() => setOpen(true)}+ onBlur={() => setTimeout(() => { if (mountedRef.current) setOpen(false); }, 120)}+ placeholder={value.length >= maxTags ? `Max ${maxTags} tags` : placeholder}+ disabled={value.length >= maxTags}+ maxLength={maxTagChars}+ className="flex-1 min-w-[8ch] bg-transparent text-white text-sm focus:outline-none disabled:opacity-50"+ />+ </div>+ {open && visibleSuggestions.length > 0 && (+ <ul className="absolute z-20 mt-1 w-full max-h-48 overflow-y-auto bg-port-card border border-port-border rounded shadow-lg">+ {visibleSuggestions.map((s) => (+ <li key={s.id}>+ {/* onMouseDown (not onClick) fires before the input's onBlur so the+ pick lands before the dropdown closes. */}+ <button+ type="button"+ onMouseDown={(e) => { e.preventDefault(); addTag(s.label); }}+ className="w-full text-left px-3 py-1.5 text-sm text-gray-200 hover:bg-port-bg flex items-center gap-2"+ >+ {s.color && (+ <span+ className="inline-block w-2 h-2 rounded-full"+ style={{ backgroundColor: s.color }}+ aria-hidden="true"+ />+ )}+ {s.label}+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}diff --git a/client/src/components/TagPicker.test.jsx b/client/src/components/TagPicker.test.jsxnew file mode 100644index 0000000000..5846605e27--- /dev/null+++ b/client/src/components/TagPicker.test.jsx@@ -0,0 +1,79 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';++vi.mock('../services/apiCatalog', () => ({+ listCatalogTags: vi.fn(),+}));++import TagPicker from './TagPicker';+import { listCatalogTags } from '../services/apiCatalog';++beforeEach(() => {+ vi.clearAllMocks();+ listCatalogTags.mockResolvedValue({ items: [] });+});++describe('TagPicker', () => {+ it('renders existing tags as removable chips', () => {+ const onChange = vi.fn();+ render(<TagPicker value={['noir', 'pulp']} onChange={onChange} />);+ expect(screen.getByText('noir')).toBeTruthy();+ expect(screen.getByText('pulp')).toBeTruthy();+ fireEvent.click(screen.getByLabelText('Remove tag noir'));+ expect(onChange).toHaveBeenCalledWith(['pulp']);+ });++ it('commits the input as a tag on Enter', () => {+ const onChange = vi.fn();+ render(<TagPicker id="tp" value={[]} onChange={onChange} />);+ const input = screen.getByRole('textbox');+ fireEvent.change(input, { target: { value: 'Noir' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).toHaveBeenCalledWith(['Noir']);+ });++ it('commits the input as a tag on comma', () => {+ const onChange = vi.fn();+ render(<TagPicker value={[]} onChange={onChange} />);+ const input = screen.getByRole('textbox');+ fireEvent.change(input, { target: { value: 'pulp' } });+ fireEvent.keyDown(input, { key: ',' });+ expect(onChange).toHaveBeenCalledWith(['pulp']);+ });++ it('dedups a casing variant of an already-selected tag (no onChange)', () => {+ const onChange = vi.fn();+ render(<TagPicker value={['Noir']} onChange={onChange} />);+ const input = screen.getByRole('textbox');+ fireEvent.change(input, { target: { value: 'NOIR' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onChange).not.toHaveBeenCalled();+ });++ it('pops the last chip on Backspace with empty input', () => {+ const onChange = vi.fn();+ render(<TagPicker value={['a', 'b']} onChange={onChange} />);+ const input = screen.getByRole('textbox');+ fireEvent.keyDown(input, { key: 'Backspace' });+ expect(onChange).toHaveBeenCalledWith(['a']);+ });++ it('shows autocomplete suggestions and adds one on click', async () => {+ listCatalogTags.mockResolvedValue({ items: [{ id: 'cat-tag-noir', label: 'noir', color: null }] });+ const onChange = vi.fn();+ render(<TagPicker value={[]} onChange={onChange} />);+ const input = screen.getByRole('textbox');+ fireEvent.focus(input);+ fireEvent.change(input, { target: { value: 'no' } });+ const suggestion = await screen.findByText('noir');+ fireEvent.mouseDown(suggestion);+ expect(onChange).toHaveBeenCalledWith(['noir']);+ });++ it('disables the input and shows a max-tags placeholder at the cap', () => {+ render(<TagPicker value={['a', 'b']} onChange={vi.fn()} maxTags={2} />);+ const input = screen.getByRole('textbox');+ expect(input.disabled).toBe(true);+ expect(input.getAttribute('placeholder')).toMatch(/Max 2 tags/);+ });+});diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.jsindex 6e796e2584..3ca5b02b40 100644--- a/client/src/lib/catalogTypes.js+++ b/client/src/lib/catalogTypes.js@@ -120,6 +120,18 @@ export const RELATION_KINDS = Object.freeze([{ id: 'related-to', label: 'Related to', inverseLabel: 'Related to' },]);+/**+ * Canonical key for a freeform tag label — client mirror of+ * `server/lib/catalogTypes.js` `canonicalTagKey`. Lowercase + trim + collapse+ * internal whitespace. Used by the tag picker to dedup the chosen-tags set+ * (so `Noir` and `noir` don't both show as chips before save). Returns `''`+ * for empty/non-string input.+ */+export function canonicalTagKey(label) {+ if (typeof label !== 'string') return '';+ return label.trim().replace(/\s+/g, ' ').toLowerCase();+}+const RELATION_BY_ID = Object.freeze(Object.fromEntries(RELATION_KINDS.map((r) => [r.id, r])));/** Look up a relation-kind entry by id. Returns `undefined` for unknown ids. */diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex c1bd53e2c9..d881583820 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -18,6 +18,7 @@ import {unlinkCatalogIngredientRelation,} from '../services/apiCatalog';import IngredientPicker from '../components/IngredientPicker';+import TagPicker from '../components/TagPicker';import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';// Per-type editor field list + badge color now come from the shared registry@@ -52,7 +53,7 @@ export default function CatalogIngredient() {const [record, setRecord] = useState(null);const [loading, setLoading] = useState(true);const [name, setName] = useState('');- const [tagsInput, setTagsInput] = useState('');+ const [tags, setTags] = useState([]);const [payload, setPayload] = useState({});const [saving, setSaving] = useState(false);const [armedDelete, setArmedDelete] = useState(false);@@ -74,7 +75,7 @@ export default function CatalogIngredient() {}setRecord(r);setName(r.name || '');- setTagsInput((r.tags || []).join(', '));+ setTags(Array.isArray(r.tags) ? r.tags : []);setPayload(r.payload && typeof r.payload === 'object' ? { ...r.payload } : {});setLoading(false);})@@ -145,7 +146,6 @@ export default function CatalogIngredient() {toast.error('Name is required');return;}- const tags = tagsInput.split(',').map((t) => t.trim()).filter(Boolean);setSaving(true);const updated = await updateCatalogIngredient(record.id, {name: trimmedName,@@ -158,6 +158,9 @@ export default function CatalogIngredient() {setSaving(false);if (!updated) return;setRecord((prev) => ({ ...prev, ...updated }));+ // The server normalizes tags through the canonical table (casing/whitespace+ // collapse), so reflect the persisted set back into the chips.+ if (Array.isArray(updated.tags)) setTags(updated.tags);toast.success('Saved');};@@ -253,11 +256,10 @@ export default function CatalogIngredient() {</div><div><label htmlFor="ingredient-tags" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">- Tags <span className="text-gray-500 normal-case">(comma-separated)</span>+ Tags</label>- <input id="ingredient-tags" type="text" value={tagsInput} onChange={(e) => setTagsInput(e.target.value)}- placeholder="mentor, antagonist, season-1"- className="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" />+ <TagPicker id="ingredient-tags" value={tags} onChange={setTags}+ placeholder="mentor, antagonist, season-1" /></div>{fields.map(([key, label, kind]) => {const inputId = `ingredient-${key}`;diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.jsindex b182b1e21e..d8ab54c558 100644--- a/client/src/services/apiCatalog.js+++ b/client/src/services/apiCatalog.js@@ -53,6 +53,17 @@ export const listCatalogIngredients = ({ type, tag, q, limit, offset, ...optionsexport const getCatalogIngredient = (id, options) =>request(`/catalog/ingredients/${enc(id)}`, options);+// --- Tags (canonical taxonomy) ------------------------------------------++// Autocomplete over the canonical catalog_tags table. `q` is an optional+// prefix/substring filter; absent returns the most-recently-created tags.+export const listCatalogTags = ({ q, limit, ...options } = {}) => {+ const params = new URLSearchParams();+ if (q) params.set('q', q);+ if (limit) params.set('limit', String(limit));+ return request(`/catalog/tags${params.toString() ? `?${params}` : ''}`, options);+};+export const createCatalogIngredient = (body = {}, options) =>request('/catalog/ingredients', { method: 'POST', body: JSON.stringify(body), ...options });diff --git a/scripts/migrations/051-catalog-tags-table.js b/scripts/migrations/051-catalog-tags-table.jsnew file mode 100644index 0000000000..2e93b69bf1--- /dev/null+++ b/scripts/migrations/051-catalog-tags-table.js@@ -0,0 +1,27 @@+/**+ * Registration stub for the catalog_tags table (tag taxonomy).+ *+ * The actual DDL — `CREATE TABLE IF NOT EXISTS catalog_tags` plus its indexes+ * and the `trg_catalog_tag_updated_at` trigger — is idempotent and lives in+ * `ensureSchema()` (`server/lib/db.js`) and the fresh-install seed+ * (`server/scripts/init-db.sql`), both of which run at server boot AFTER the DB+ * pool is up. The `scripts/migrations/` runner executes BEFORE the pool is+ * initialized, so a DB-table create cannot live here — the same reason+ * migrations 048/049/050 are boot-time + stub-registered.+ *+ * This stub exists so the tag-taxonomy change is *registered the standard way*:+ * it lands in `data/migrations.applied.json` so the migration ledger and+ * `git log` show when the canonical tag table was introduced. The table is+ * additive (a brand-new table; the freeform `catalog_ingredients.tags TEXT[]`+ * column is unchanged), so there is no data backfill to perform here —+ * `catalogDB.normalizeTags` populates `catalog_tags` lazily on the next+ * ingredient create/update.+ *+ * No-op + idempotent: nothing to do here.+ */++export default {+ async up() {+ console.log('🏷️ catalog_tags: table created idempotently by ensureSchema at boot; nothing to do in the file runner');+ },+};diff --git a/server/lib/README.md b/server/lib/README.mdindex b54047f041..6f440ab947 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -26,7 +26,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `validation.js` | Catch-all Zod schemas + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`). Most route inputs validate through here. || `appleHealthValidation.js` | Apple Health import payloads. || `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |-| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, sync envelope). |+| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, sync envelope). || `digitalTwinValidation.js` | Digital twin document/category schemas. || `genomeValidation.js` | Genome upload + search schemas. || `identityValidation.js` | Identity section + chronotype + scheduling schemas. |@@ -51,7 +51,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `seasonStructure.js` | Season/episode structure recommendation. || `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. Mirrored on the client at `client/src/lib/catalogTypes.js`. |+| `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`. || `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/catalogTypes.js b/server/lib/catalogTypes.jsindex 4eb07488a8..1ce54af31b 100644--- a/server/lib/catalogTypes.js+++ b/server/lib/catalogTypes.js@@ -49,6 +49,10 @@ import { BIBLE_LIMITS } from './storyBible.js';* (the bundled ideas/scenes/concepts LLM stage).* payloadSchemaVersion — current per-record payload-shape version.* payloadUpgraders — { <fromVersion>: (payload) => payload } chain.+ * defaultTags — canonical tag labels seeded onto every freshly-+ * created ingredient of this type (optional). Used by+ * the tag-normalization step so a new `scene` row+ * picks up `scene` etc. without the user typing it.*/const REGISTRY = [{@@ -63,6 +67,7 @@ const REGISTRY = [extractionShape: 'bible',payloadSchemaVersion: 1,payloadUpgraders: {},+ defaultTags: [],},{id: 'place',@@ -76,6 +81,7 @@ const REGISTRY = [extractionShape: 'bible',payloadSchemaVersion: 1,payloadUpgraders: {},+ defaultTags: [],},{id: 'object',@@ -89,6 +95,7 @@ const REGISTRY = [extractionShape: 'bible',payloadSchemaVersion: 1,payloadUpgraders: {},+ defaultTags: [],},{id: 'idea',@@ -102,6 +109,7 @@ const REGISTRY = [extractionShape: 'light',payloadSchemaVersion: 1,payloadUpgraders: {},+ defaultTags: [],},{id: 'scene',@@ -115,6 +123,7 @@ const REGISTRY = [extractionShape: 'light',payloadSchemaVersion: 1,payloadUpgraders: {},+ defaultTags: [],},{id: 'concept',@@ -128,6 +137,7 @@ const REGISTRY = [extractionShape: 'light',payloadSchemaVersion: 1,payloadUpgraders: {},+ defaultTags: [],},];@@ -152,6 +162,9 @@ for (const t of REGISTRY) {if (t.payloadUpgraders && typeof t.payloadUpgraders !== 'object') {throw new Error(`catalogTypes: "${t.id}" payloadUpgraders must be an object`);}+ if (t.defaultTags !== undefined && !Array.isArray(t.defaultTags)) {+ throw new Error(`catalogTypes: "${t.id}" defaultTags must be an array`);+ }}export const CATALOG_TYPES = Object.freeze(REGISTRY.map((t) => Object.freeze({ ...t })));@@ -193,6 +206,41 @@ export function currentPayloadSchemaVersion(id) {return BY_ID[id]?.payloadSchemaVersion ?? 1;}+/**+ * Registry-declared default tags for a type — seeded onto a freshly-created+ * ingredient so e.g. a new `scene` row picks up its type's default tags+ * automatically. Returns a fresh array (never the frozen registry array) so a+ * caller can mutate/merge without poisoning the registry. Unknown type → `[]`.+ */+export function defaultTagsForType(id) {+ return [...(BY_ID[id]?.defaultTags || [])];+}++// --- Tag taxonomy --------------------------------------------------------+// `catalog_tags` promotes the freeform `catalog_ingredients.tags TEXT[]` to a+// first-class table (id, label, description?, color?, parent_id?). The freeform+// column stays for write-path simplicity; the normalizer below maps user input+// through a canonical KEY so `Noir` / `noir` / ` noir ` collapse to one row.++/** Mint the `cat-tag-<slug>` deterministic id for a canonical tag key. */+export function tagIdForKey(key) {+ return `cat-tag-${key}`;+}++/**+ * Canonical key for a freeform tag label — the dedup discriminant for the+ * `catalog_tags` table. Lowercase + trim + collapse internal whitespace to a+ * single space. This intentionally does NOT fold `noir` and `film-noir` into+ * one (that's a synonym judgment the user makes via `parent_id`), but it DOES+ * collapse `Noir`, `noir`, and ` noir ` so casing/whitespace variants don't+ * accumulate as separate rows. Returns `''` for empty/non-string input so the+ * caller can drop it.+ */+export function canonicalTagKey(label) {+ if (typeof label !== 'string') return '';+ return label.trim().replace(/\s+/g, ' ').toLowerCase();+}+/*** Catalog ingredient↔ingredient RELATION kinds.*diff --git a/server/lib/catalogTypes.test.js b/server/lib/catalogTypes.test.jsindex 5b09f6039f..61aef22541 100644--- a/server/lib/catalogTypes.test.js+++ b/server/lib/catalogTypes.test.js@@ -27,6 +27,9 @@ import {RELATION_KINDS,RELATION_KIND_IDS,getRelationKind,+ canonicalTagKey,+ tagIdForKey,+ defaultTagsForType,} from './catalogTypes.js';import { INGREDIENT_TYPES } from './catalogValidation.js';@@ -176,6 +179,48 @@ describe('catalogTypes — payload schemaVersion', () => {});});+describe('catalogTypes — tag taxonomy helpers', () => {+ it('canonicalTagKey lowercases, trims, and collapses whitespace', () => {+ expect(canonicalTagKey('Noir')).toBe('noir');+ expect(canonicalTagKey(' noir ')).toBe('noir');+ expect(canonicalTagKey('Film Noir')).toBe('film noir');+ expect(canonicalTagKey('FILM NOIR')).toBe('film noir');+ });++ it('canonicalTagKey returns "" for empty / non-string input', () => {+ expect(canonicalTagKey('')).toBe('');+ expect(canonicalTagKey(' ')).toBe('');+ expect(canonicalTagKey(null)).toBe('');+ expect(canonicalTagKey(undefined)).toBe('');+ expect(canonicalTagKey(42)).toBe('');+ });++ it('canonicalTagKey does NOT fold distinct labels (synonyms stay separate)', () => {+ // `noir` and `film-noir` are different keys — synonym merging is the user's+ // job via parent_id, not the normalizer's.+ expect(canonicalTagKey('noir')).not.toBe(canonicalTagKey('film-noir'));+ });++ it('tagIdForKey builds a deterministic cat-tag-<key> id', () => {+ expect(tagIdForKey('noir')).toBe('cat-tag-noir');+ expect(tagIdForKey(canonicalTagKey('Film Noir'))).toBe('cat-tag-film noir');+ });++ it('defaultTagsForType returns a fresh array, never the frozen registry one', () => {+ const a = defaultTagsForType('character');+ const b = defaultTagsForType('character');+ expect(Array.isArray(a)).toBe(true);+ expect(a).not.toBe(b); // distinct copies — safe to mutate+ expect(defaultTagsForType('nope')).toEqual([]);+ });++ it('every registry entry has an array defaultTags', () => {+ for (const t of CATALOG_TYPES) {+ expect(Array.isArray(t.defaultTags)).toBe(true);+ }+ });+});+describe('catalogTypes — relation kinds', () => {it('exposes the documented relation kinds, frozen + unique', () => {expect(Object.isFrozen(RELATION_KINDS)).toBe(true);diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex bbde775fe4..64f96f3cfd 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -75,6 +75,14 @@ export const catalogIngredientQuerySchema = z.object({offset: z.coerce.number().int().min(0).optional(),}).strict();+// Tag-autocomplete query — `q` is an optional prefix/substring filter, absent+// returns the most-recently-created tags. Drives the tag-picker autocomplete on+// CatalogIngredient.jsx + the Quick Idea widget.+export const catalogTagQuerySchema = z.object({+ q: z.string().trim().max(BIBLE_LIMITS.TAG_MAX).optional(),+ limit: z.coerce.number().int().min(1).max(100).optional(),+}).strict();+export const catalogIngredientLinkSchema = z.object({refKind: z.enum(REF_KINDS),refId: z.string().trim().min(1).max(120),@@ -250,11 +258,27 @@ const portosMeta = z.object({{ message: 'portosMeta exceeds 4KB size cap' },).optional();+// Canonical tag rows on the wire. `label` carries the first-seen casing; the+// mutable fields (description/color/parentId) round-trip via LWW on updatedAt.+// `parentId` is freeform (the receiver's parent-less retry tolerates a parent+// that hasn't arrived yet), so no enum/FK gate here.+export const catalogSyncTagSchema = z.object({+ id: z.string().min(1).max(120),+ label: z.string().max(BIBLE_LIMITS.TAG_MAX),+ description: z.string().max(2_000).nullable().optional(),+ color: z.string().max(32).nullable().optional(),+ parentId: z.string().max(120).nullable().optional(),+ createdAt: isoDate,+ updatedAt: isoDate.optional(),+ syncSequence: z.string().optional(),+}).passthrough();+export const catalogSyncEnvelopeSchema = z.object({scraps: z.array(catalogSyncScrapSchema).max(5_000).optional(),ingredients: z.array(catalogSyncIngredientSchema).max(5_000).optional(),sources: z.array(catalogSyncSourceSchema).max(20_000).optional(),refs: z.array(catalogSyncRefSchema).max(20_000).optional(),relations: z.array(catalogSyncRelationSchema).max(20_000).optional(),+ tags: z.array(catalogSyncTagSchema).max(20_000).optional(),portosMeta,}).passthrough();diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 21a6996906..112236ccb1 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -29,6 +29,7 @@ const CATALOG_TABLES = ['catalog_ingredient_sources','catalog_ingredient_refs','catalog_ingredient_relations',+ 'catalog_tags',];// Strip line comments + collapse whitespace so column lists compare cleanly.diff --git a/server/lib/db.js b/server/lib/db.jsindex f90ce3fe68..fe46ea083c 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -253,6 +253,25 @@ export async function ensureSchema() {`CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_to ON catalog_ingredient_relations (to_id)`,`CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_sync_seq ON catalog_ingredient_relations (sync_sequence)`,+ // First-class canonical tag table. Additive index over the freeform+ // `catalog_ingredients.tags TEXT[]` column (which stays as-is). `id` is+ // deterministic (`cat-tag-<canonical-key>`) so the same tag has the same id+ // on every install; `parent_id` self-FK (ON DELETE SET NULL) enables tag+ // hierarchies without cascading a subtree away.+ `CREATE TABLE IF NOT EXISTS catalog_tags (+ id TEXT PRIMARY KEY,+ label TEXT NOT NULL,+ description TEXT,+ color VARCHAR(32),+ parent_id TEXT REFERENCES catalog_tags(id) ON DELETE SET NULL,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ sync_sequence BIGSERIAL+ )`,+ `CREATE INDEX IF NOT EXISTS idx_catalog_tags_label ON catalog_tags (label)`,+ `CREATE INDEX IF NOT EXISTS idx_catalog_tags_parent ON catalog_tags (parent_id)`,+ `CREATE INDEX IF NOT EXISTS idx_catalog_tags_sync_seq ON catalog_tags (sync_sequence)`,+`CREATE OR REPLACE FUNCTION update_catalog_ingredient_timestamp()RETURNS TRIGGER AS $$DECLARE@@ -368,6 +387,35 @@ export async function ensureSchema() {BEFORE UPDATE ON catalog_ingredient_relationsFOR EACH ROWEXECUTE FUNCTION update_catalog_relation_sync_seq()`,++ // Tag UPDATE bumps sync_sequence + updated_at on a mutable-field change+ // (label/description/color/parent_id) so a peer sees the edit on its next+ // pull. Mirrors the scrap timestamp trigger.+ `CREATE OR REPLACE FUNCTION update_catalog_tag_timestamp()+ RETURNS TRIGGER AS $$+ DECLARE+ content_changed BOOLEAN;+ BEGIN+ content_changed := (+ NEW.label IS DISTINCT FROM OLD.label OR+ NEW.description IS DISTINCT FROM OLD.description OR+ NEW.color IS DISTINCT FROM OLD.color OR+ NEW.parent_id IS DISTINCT FROM OLD.parent_id OR+ NEW.updated_at IS DISTINCT FROM OLD.updated_at+ );+ IF NOT content_changed THEN RETURN NEW; END IF;+ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN+ NEW.updated_at := NOW();+ END IF;+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_tags', 'sync_sequence'));+ RETURN NEW;+ END;+ $$ LANGUAGE plpgsql`,+ `DROP TRIGGER IF EXISTS trg_catalog_tag_updated_at ON catalog_tags`,+ `CREATE TRIGGER trg_catalog_tag_updated_at+ BEFORE UPDATE ON catalog_tags+ FOR EACH ROW+ EXECUTE FUNCTION update_catalog_tag_timestamp()`,];for (const sql of catalogDDL) {await pool.query(sql);diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex c4f178c029..c757bf389a 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -84,7 +84,16 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// since the older peer would silently drop every relation edge. v4 receivers// still accept ≤v3 senders (sender-behind): those envelopes simply carry no// `relations` block and the receiver applies the other four kinds as before.- catalog: 4,+ // v5 = `catalog_tags` first-class table (id, label, description?, color?,+ // parent_id?, created_at, sync_sequence) + a new `tags: [...]` block in the+ // catalog sync envelope. Same gating rationale as v4: a ≤v4 receiver doesn't+ // understand the `tags` block, so a v5 sender pushing to it is sender-ahead+ // and gets a 412 (otherwise the older peer would silently drop every canonical+ // tag row + its parent hierarchy). The freeform `catalog_ingredients.tags+ // TEXT[]` column is unchanged — canonical tag rows are an additive index, so+ // a v5 receiver still accepts ≤v4 ingredient/scrap/ref/relation pushes; those+ // envelopes simply carry no `tags` block.+ catalog: 5,// NOTE: `videoHistory` is intentionally NOT listed here. The version gate// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the// comparator walks the union of keys), so declaring a brand-new key woulddiff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex bff57f0b46..28ae493e46 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -15,6 +15,7 @@ import {catalogIngredientLinkSchema,catalogRelationLinkSchema,catalogIngredientQuerySchema,+ catalogTagQuerySchema,catalogScrapCommitSchema,catalogSyncEnvelopeSchema,catalogExtractRequestSchema,@@ -126,6 +127,13 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {res.status(201).json({ scrap, ingredients: created });}));+// Tag-picker autocomplete. `?q=` does a prefix-then-substring match on the+// canonical tag labels; absent `q` returns the most-recently-created tags.+router.get('/tags', asyncHandler(async (req, res) => {+ const params = validateRequest(catalogTagQuerySchema, req.query);+ res.json(await catalogDB.listTags({ q: params.q, limit: params.limit ?? 20 }));+}));+router.get('/ingredients', asyncHandler(async (req, res) => {const params = validateRequest(catalogIngredientQuerySchema, req.query);res.json(await catalogDB.listIngredients({diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex f55275108b..f075d6c177 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -273,6 +273,30 @@ CREATE TABLE IF NOT EXISTS catalog_ingredient_relations (CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_to ON catalog_ingredient_relations (to_id);CREATE INDEX IF NOT EXISTS idx_catalog_ing_relations_sync_seq ON catalog_ingredient_relations (sync_sequence);+-- First-class canonical tag table. The freeform `catalog_ingredients.tags+-- TEXT[]` column stays as-is for write-path simplicity; this table is an+-- additive index that the normalizer (catalogDB.normalizeTags) populates on+-- first use of a tag. `id` is deterministic (`cat-tag-<canonical-key>`) so the+-- same logical tag has the same id on every install. `parent_id` is an optional+-- self-FK enabling tag hierarchies (genre/tone vs structural). Federates via+-- sync_sequence BIGSERIAL + LWW on created_at (tags are append-mostly; the+-- mutable fields — label/description/color/parent_id — round-trip through the+-- trigger below). `ON DELETE SET NULL` on the parent self-FK keeps orphaned+-- children rather than cascading a whole subtree away.+CREATE TABLE IF NOT EXISTS catalog_tags (+ id TEXT PRIMARY KEY,+ label TEXT NOT NULL, -- canonical display label (first-seen casing)+ description TEXT,+ color VARCHAR(32),+ parent_id TEXT REFERENCES catalog_tags(id) ON DELETE SET NULL,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ sync_sequence BIGSERIAL+);+CREATE INDEX IF NOT EXISTS idx_catalog_tags_label ON catalog_tags (label);+CREATE INDEX IF NOT EXISTS idx_catalog_tags_parent ON catalog_tags (parent_id);+CREATE INDEX IF NOT EXISTS idx_catalog_tags_sync_seq ON catalog_tags (sync_sequence);+-- Auto-update updated_at and bump sync_sequence on content/metadata changes.-- Mirrors update_memory_timestamp's pattern: skip the bump on no-content-change-- so cosmetic touches don't trigger sync. Respects explicit updated_at (used by@@ -405,3 +429,38 @@ CREATE TRIGGER trg_catalog_relation_sync_seqBEFORE UPDATE ON catalog_ingredient_relationsFOR EACH ROWEXECUTE FUNCTION update_catalog_relation_sync_seq();++-- Tag UPDATE bumps sync_sequence + updated_at when a mutable field changes+-- (label/description/color/parent_id) so peers receive the edit on their next+-- pull. Respects an explicit updated_at (the sync apply path preserves the+-- originating timestamp during LWW merges). Mirrors the scrap timestamp trigger.+CREATE OR REPLACE FUNCTION update_catalog_tag_timestamp()+RETURNS TRIGGER AS $$+DECLARE+ content_changed BOOLEAN;+BEGIN+ content_changed := (+ NEW.label IS DISTINCT FROM OLD.label OR+ NEW.description IS DISTINCT FROM OLD.description OR+ NEW.color IS DISTINCT FROM OLD.color OR+ NEW.parent_id IS DISTINCT FROM OLD.parent_id OR+ NEW.updated_at IS DISTINCT FROM OLD.updated_at+ );++ IF NOT content_changed THEN+ RETURN NEW;+ END IF;++ IF NEW.updated_at IS NULL OR NEW.updated_at = OLD.updated_at THEN+ NEW.updated_at := NOW();+ END IF;+ NEW.sync_sequence := nextval(pg_get_serial_sequence('catalog_tags', 'sync_sequence'));+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS trg_catalog_tag_updated_at ON catalog_tags;+CREATE TRIGGER trg_catalog_tag_updated_at+ BEFORE UPDATE ON catalog_tags+ FOR EACH ROW+ EXECUTE FUNCTION update_catalog_tag_timestamp();diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex 3d345dd2aa..2f7ddf8b0f 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -15,6 +15,9 @@ import {getCatalogType,ingredientIdPrefix,currentPayloadSchemaVersion,+ canonicalTagKey,+ tagIdForKey,+ defaultTagsForType,} from '../lib/catalogTypes.js';import { getInstanceId } from './instances.js';@@ -103,6 +106,20 @@ function rowToSource(row) {};}+function rowToTag(row) {+ if (!row) return null;+ return {+ id: row.id,+ label: row.label,+ description: row.description ?? null,+ color: row.color ?? null,+ parentId: row.parent_id ?? null,+ createdAt: row.created_at.toISOString(),+ updatedAt: row.updated_at.toISOString(),+ syncSequence: String(row.sync_sequence),+ };+}+export async function createScrap({ title, rawText, sourceKind = 'paste', metadata = {}, embedding = null, embeddingModel = null } = {}) {if (!rawText) throw new Error('rawText is required');@@ -220,6 +237,11 @@ export async function createIngredient({ id: explicitId, type, name, payload = {const storedPayload = { ...(payload && typeof payload === 'object' ? payload : {}), schemaVersion: currentPayloadSchemaVersion(type) };const originInstanceId = await getInstanceId();const exec = client ? client.query.bind(client) : query;+ // Route freeform tags through the canonical catalog_tags table (creating+ // rows on first use) and seed the type's registry default tags. The freeform+ // TEXT[] column stores the canonical labels so existing tag-search/GIN paths+ // keep working unchanged.+ const normalizedTags = await normalizeTags([...defaultTagsForType(type), ...(tags || [])], { client });const result = await exec(`INSERT INTO catalog_ingredients(id, type, name, payload, tags, embedding, embedding_model, origin_instance_id)@@ -230,7 +252,7 @@ export async function createIngredient({ id: explicitId, type, name, payload = {type,String(name).trim(),JSON.stringify(storedPayload),- tags || [],+ normalizedTags,embedding ? arrayToPgvector(embedding) : null,embeddingModel,originInstanceId,@@ -251,6 +273,13 @@ export async function updateIngredient(id, patch = {}) {const fields = [];const params = [];let idx = 1;+ // Normalize freeform tags through the canonical table on edit too — a user+ // adding `Noir` reuses the existing `noir` row instead of accumulating a+ // casing variant. `tags: []` (intentional clear) round-trips as an empty+ // array; absent `tags` skips normalization entirely (the loop below skips it).+ const normalizedPatch = patch.tags !== undefined+ ? { ...patch, tags: await normalizeTags(patch.tags) }+ : patch;const fieldMap = {name: 'name',payload: 'payload',@@ -259,16 +288,16 @@ export async function updateIngredient(id, patch = {}) {embeddingModel: 'embedding_model',};for (const [jsField, dbField] of Object.entries(fieldMap)) {- if (patch[jsField] === undefined) continue;+ if (normalizedPatch[jsField] === undefined) continue;if (jsField === 'payload') {fields.push(`${dbField} = $${idx++}::jsonb`);- params.push(JSON.stringify(patch.payload || {}));+ params.push(JSON.stringify(normalizedPatch.payload || {}));} else if (jsField === 'embedding') {fields.push(`${dbField} = $${idx++}`);- params.push(patch.embedding ? arrayToPgvector(patch.embedding) : null);+ params.push(normalizedPatch.embedding ? arrayToPgvector(normalizedPatch.embedding) : null);} else {fields.push(`${dbField} = $${idx++}`);- params.push(patch[jsField]);+ params.push(normalizedPatch[jsField]);}}if (fields.length === 0) return getIngredient(id);@@ -610,6 +639,164 @@ export async function upsertRelationFromPeer(rel) {}+// --- Tag taxonomy --------------------------------------------------------+// `catalog_tags` is the canonical index over the freeform+// `catalog_ingredients.tags TEXT[]` column. `normalizeTags` maps user input+// through it (creating rows on first use, deterministic `cat-tag-<key>` ids)+// and returns the de-duplicated canonical label list to store in the array+// column. The freeform column keeps working unchanged for GIN tag-search.++/**+ * Map a list of freeform tag labels to canonical labels, creating a+ * `catalog_tags` row per unique canonical key on first use. Returns the+ * de-duplicated, order-preserving list of canonical labels (first-seen casing+ * wins, both within this call and against any pre-existing row). Empty / blank+ * tags are dropped. `{ client }` runs the upserts on the caller's transaction.+ */+export async function normalizeTags(labels = [], { client } = {}) {+ if (!Array.isArray(labels) || labels.length === 0) return [];+ const exec = client ? client.query.bind(client) : query;+ const out = [];+ const seen = new Set();+ for (const raw of labels) {+ const key = canonicalTagKey(raw);+ if (!key || seen.has(key)) continue;+ seen.add(key);+ const id = tagIdForKey(key);+ const label = String(raw).trim().replace(/\s+/g, ' ');+ // First write wins on the canonical label — ON CONFLICT DO NOTHING keeps+ // the original casing rather than letting a later `NOIR` overwrite `Noir`.+ // RETURNING after a no-op conflict is empty, so re-select to read the+ // stored canonical label for the array column.+ const ins = await exec(+ `INSERT INTO catalog_tags (id, label)+ VALUES ($1, $2)+ ON CONFLICT (id) DO NOTHING+ RETURNING label`,+ [id, label],+ );+ if (ins.rows[0]?.label) {+ out.push(ins.rows[0].label);+ } else {+ const existing = await exec(`SELECT label FROM catalog_tags WHERE id = $1`, [id]);+ out.push(existing.rows[0]?.label ?? label);+ }+ }+ return out;+}++export async function getTag(id) {+ const result = await query(`SELECT * FROM catalog_tags WHERE id = $1`, [id]);+ return rowToTag(result.rows[0]);+}++/**+ * Autocomplete / list canonical tags. `q` does a case-insensitive prefix-then-+ * substring match on label (prefix matches rank first); absent `q` returns the+ * most-recently-created tags. Drives the tag-picker autocomplete.+ */+export async function listTags({ q, limit = 20 } = {}) {+ const lim = Math.min(Math.max(parseInt(limit, 10) || 20, 1), 100);+ if (q && String(q).trim()) {+ const term = String(q).trim();+ const result = await query(+ `SELECT * FROM catalog_tags+ WHERE label ILIKE $1+ ORDER BY+ CASE WHEN label ILIKE $2 THEN 0 ELSE 1 END,+ label ASC+ LIMIT $3`,+ [`%${term}%`, `${term}%`, lim],+ );+ return { items: result.rows.map(rowToTag) };+ }+ const result = await query(+ `SELECT * FROM catalog_tags ORDER BY created_at DESC LIMIT $1`,+ [lim],+ );+ return { items: result.rows.map(rowToTag) };+}++/**+ * Patch a tag's mutable fields (description / color / parent_id). `label` is+ * intentionally NOT patchable here — relabeling would orphan the freeform+ * array values that reference the old casing. Self-parent is rejected.+ */+export async function updateTag(id, patch = {}) {+ const fields = [];+ const params = [];+ let idx = 1;+ const fieldMap = { description: 'description', color: 'color', parentId: 'parent_id' };+ for (const [jsField, dbField] of Object.entries(fieldMap)) {+ if (patch[jsField] === undefined) continue;+ if (jsField === 'parentId' && patch.parentId === id) {+ throw new Error('a tag cannot be its own parent');+ }+ fields.push(`${dbField} = $${idx++}`);+ params.push(patch[jsField] === '' ? null : patch[jsField]);+ }+ if (fields.length === 0) return getTag(id);+ params.push(id);+ const result = await query(+ `UPDATE catalog_tags SET ${fields.join(', ')} WHERE id = $${idx} RETURNING *`,+ params,+ );+ return rowToTag(result.rows[0]);+}++export async function getTagChangesSince(since = '0', limit = 100) {+ const result = await query(+ `SELECT * FROM catalog_tags WHERE sync_sequence > $1 ORDER BY sync_sequence ASC LIMIT $2`,+ [since, limit + 1],+ );+ const hasMore = result.rows.length > limit;+ const rows = hasMore ? result.rows.slice(0, limit) : result.rows;+ return { items: rows.map(rowToTag), hasMore };+}++export async function upsertTagFromPeer(tag) {+ // LWW on updated_at for the mutable fields (description/color/parent_id) ++ // label. `parent_id` may FK to a tag that hasn't arrived yet in this envelope+ // — the receiver orders tags before ingredients, but a parent can still lag a+ // child across pages. We retry parent-less first: NULL the parent on FK+ // violation so the child row still lands, and a later page carrying the+ // parent re-runs this upsert (LWW) to restore the link.+ const apply = async (parentId) => query(+ `INSERT INTO catalog_tags+ (id, label, description, color, parent_id, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ ON CONFLICT (id) DO UPDATE SET+ label = EXCLUDED.label,+ description = EXCLUDED.description,+ color = EXCLUDED.color,+ parent_id = EXCLUDED.parent_id,+ updated_at = EXCLUDED.updated_at+ WHERE EXCLUDED.updated_at > catalog_tags.updated_at+ RETURNING (xmax = 0) AS is_insert`,+ [+ tag.id,+ tag.label,+ tag.description ?? null,+ tag.color ?? null,+ parentId ?? null,+ tag.createdAt,+ tag.updatedAt || tag.createdAt,+ ],+ );+ let result;+ try {+ result = await apply(tag.parentId ?? null);+ } catch (err) {+ // 23503 = foreign_key_violation (parent not present yet). Retry parent-less.+ if (err?.code === '23503' && (tag.parentId ?? null) !== null) {+ result = await apply(null);+ } else {+ throw err;+ }+ }+ return { applied: result.rows.length > 0, isInsert: result.rows[0]?.is_insert ?? false };+}+export async function getMaxSequences() {const result = await query(`SELECT@@ -617,7 +804,8 @@ export async function getMaxSequences() {COALESCE((SELECT MAX(sync_sequence) FROM catalog_scraps), 0)::text AS scraps,COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_sources), 0)::text AS sources,COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_refs), 0)::text AS refs,- COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_relations), 0)::text AS relations+ COALESCE((SELECT MAX(sync_sequence) FROM catalog_ingredient_relations), 0)::text AS relations,+ COALESCE((SELECT MAX(sync_sequence) FROM catalog_tags), 0)::text AS tags`);return result.rows[0];}diff --git a/server/services/catalogDB.tags.test.js b/server/services/catalogDB.tags.test.jsnew file mode 100644index 0000000000..86117dc89e--- /dev/null+++ b/server/services/catalogDB.tags.test.js@@ -0,0 +1,109 @@+/**+ * Unit tests for the catalog tag-taxonomy DB helpers (`normalizeTags`,+ * `upsertTagFromPeer`). Postgres is mocked with an in-memory `catalog_tags`+ * map so the suite runs without a live database — we assert on the canonical+ * dedup behavior + first-write-wins casing + the peer parent-less retry.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++// In-memory tag store keyed by id. The mock interprets the three SQL shapes+// normalizeTags / upsertTagFromPeer issue: INSERT … ON CONFLICT DO NOTHING+// RETURNING label, SELECT label WHERE id, and the peer LWW upsert.+const tagStore = new Map();+let failParentFkOnce = false;++vi.mock('../lib/db.js', () => ({+ query: vi.fn(async (sql, params) => {+ if (/INSERT INTO catalog_tags[\s\S]*ON CONFLICT \(id\) DO NOTHING/.test(sql)) {+ const [id, label] = params;+ if (tagStore.has(id)) return { rows: [] }; // conflict → DO NOTHING+ tagStore.set(id, { id, label });+ return { rows: [{ label }] };+ }+ if (/^SELECT label FROM catalog_tags WHERE id/.test(sql.trim())) {+ const [id] = params;+ const row = tagStore.get(id);+ return { rows: row ? [{ label: row.label }] : [] };+ }+ if (/INSERT INTO catalog_tags[\s\S]*ON CONFLICT \(id\) DO UPDATE/.test(sql)) {+ const [id, label, description, color, parentId] = params;+ if (failParentFkOnce && parentId) {+ failParentFkOnce = false;+ const err = new Error('insert or update violates foreign key constraint');+ err.code = '23503';+ throw err;+ }+ const isInsert = !tagStore.has(id);+ tagStore.set(id, { id, label, description, color, parentId });+ return { rows: [{ is_insert: isInsert }] };+ }+ return { rows: [] };+ }),+ withTransaction: vi.fn(),+ pgvectorToArray: vi.fn(() => null),+ arrayToPgvector: vi.fn((a) => a),+}));++vi.mock('./instances.js', () => ({ getInstanceId: vi.fn(async () => 'inst-test') }));++import { normalizeTags, upsertTagFromPeer } from './catalogDB.js';++beforeEach(() => {+ tagStore.clear();+ failParentFkOnce = false;+ vi.clearAllMocks();+});++describe('normalizeTags', () => {+ it('returns [] for empty / non-array input', async () => {+ expect(await normalizeTags([])).toEqual([]);+ expect(await normalizeTags(undefined)).toEqual([]);+ expect(await normalizeTags(null)).toEqual([]);+ });++ it('dedups casing/whitespace variants within one call (first wins)', async () => {+ const out = await normalizeTags(['Noir', 'noir', ' NOIR ']);+ expect(out).toEqual(['Noir']);+ // One canonical row created.+ expect(tagStore.has('cat-tag-noir')).toBe(true);+ expect(tagStore.get('cat-tag-noir').label).toBe('Noir');+ });++ it('reuses the existing canonical label across calls (stored casing wins)', async () => {+ await normalizeTags(['Noir']);+ const out = await normalizeTags(['NOIR', 'pulp']);+ // The pre-existing `Noir` row's casing is returned, not the new `NOIR`.+ expect(out).toEqual(['Noir', 'pulp']);+ });++ it('drops blank tags and collapses internal whitespace in the stored label', async () => {+ const out = await normalizeTags(['', ' ', 'Film Noir']);+ expect(out).toEqual(['Film Noir']);+ expect(tagStore.has('cat-tag-film noir')).toBe(true);+ });++ it('preserves order of first appearance', async () => {+ const out = await normalizeTags(['beta', 'alpha', 'beta', 'gamma']);+ expect(out).toEqual(['beta', 'alpha', 'gamma']);+ });+});++describe('upsertTagFromPeer', () => {+ it('inserts a new tag and reports isInsert', async () => {+ const res = await upsertTagFromPeer({ id: 'cat-tag-noir', label: 'Noir', createdAt: 't', updatedAt: 't' });+ expect(res).toEqual({ applied: true, isInsert: true });+ expect(tagStore.get('cat-tag-noir').label).toBe('Noir');+ });++ it('retries parent-less on an FK violation so the child row still lands', async () => {+ failParentFkOnce = true; // first attempt (with parent) throws 23503+ const res = await upsertTagFromPeer({+ id: 'cat-tag-child', label: 'Child', parentId: 'cat-tag-missing',+ createdAt: 't', updatedAt: 't',+ });+ expect(res.applied).toBe(true);+ // Row landed with a null parent (the parent can re-link on a later page).+ expect(tagStore.get('cat-tag-child').parentId).toBeNull();+ });+});diff --git a/server/services/catalogSync.js b/server/services/catalogSync.jsindex 9a8f662b0f..2706892e7b 100644--- a/server/services/catalogSync.js+++ b/server/services/catalogSync.js@@ -2,13 +2,13 @@* Catalog Federation Sync Service** Peer-to-peer sync for the Creative Ingredients Catalog. Mirrors- * server/services/memorySync.js but the envelope carries five kinds- * (scraps, ingredients, sources, refs, relations) because the catalog is a- * multi-table relational store, not a single flat row set.+ * server/services/memorySync.js but the envelope carries six kinds+ * (scraps, ingredients, sources, refs, relations, tags) because the catalog is+ * a multi-table relational store, not a single flat row set.** Pull protocol:- * GET /api/catalog/sync?since[scraps]=A&since[ingredients]=B&...&since[relations]=E&limit=100- * → { scraps[], ingredients[], sources[], refs[], relations[], maxSequences, hasMore }+ * GET /api/catalog/sync?since[scraps]=A&since[ingredients]=B&...&since[tags]=F&limit=100+ * → { scraps[], ingredients[], sources[], refs[], relations[], tags[], maxSequences, hasMore }** The BIGSERIAL `sync_sequence` columns are INDEPENDENT — a row at* sources.sync_sequence=50 isn't comparable to ingredients.sync_sequence=50.@@ -31,16 +31,18 @@ import {getSourceChangesSince,getRefChangesSince,getRelationChangesSince,+ getTagChangesSince,getMaxSequences,upsertScrapFromPeer,upsertIngredientFromPeer,upsertSourceFromPeer,upsertRefFromPeer,upsertRelationFromPeer,+ upsertTagFromPeer,} from './catalogDB.js';import { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';-const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations'];+const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags'];// Normalize `since` (scalar string OR per-kind object) into a `{ scraps,// ingredients, sources, refs }` cursor map. Scalar form is uniform across@@ -60,16 +62,18 @@ function normalizeCursors(since) {export async function getChangesSince(since = '0', limit = 100) {const cursors = normalizeCursors(since);- const [scraps, ingredients, sources, refs, relations] = await Promise.all([+ const [scraps, ingredients, sources, refs, relations, tags] = await Promise.all([getScrapChangesSince(cursors.scraps, limit),getIngredientChangesSince(cursors.ingredients, limit),getSourceChangesSince(cursors.sources, limit),getRefChangesSince(cursors.refs, limit),getRelationChangesSince(cursors.relations, limit),+ getTagChangesSince(cursors.tags, limit),]);const hasMore =- scraps.hasMore || ingredients.hasMore || sources.hasMore || refs.hasMore || relations.hasMore;+ scraps.hasMore || ingredients.hasMore || sources.hasMore || refs.hasMore ||+ relations.hasMore || tags.hasMore;// Per-kind cursor advance — fall back to the inbound cursor so the next pull// doesn't move backward on a quiet kind.@@ -82,12 +86,14 @@ export async function getChangesSince(since = '0', limit = 100) {sources: sources.items,refs: refs.items,relations: relations.items,+ tags: tags.items,maxSequences: {scraps: maxOf(scraps.items, cursors.scraps),ingredients: maxOf(ingredients.items, cursors.ingredients),sources: maxOf(sources.items, cursors.sources),refs: maxOf(refs.items, cursors.refs),relations: maxOf(relations.items, cursors.relations),+ tags: maxOf(tags.items, cursors.tags),},hasMore,};@@ -120,6 +126,7 @@ export async function applyRemoteChanges(envelope = {}) {sources: { applied: 0, failed: 0 },refs: { applied: 0, failed: 0 },relations: { applied: 0, failed: 0 },+ tags: { inserted: 0, updated: 0, skipped: 0, failed: 0 },errors: [],};@@ -128,7 +135,24 @@ export async function applyRemoteChanges(envelope = {}) {console.error(`❌ catalog sync ${kind} ${id || '?'} failed: ${err?.message || err}`);};- // Scraps first (sources FK to BOTH so we want the parents present before+ // Tags first — they carry a `parent_id` self-FK (handled by the parent-less+ // retry in upsertTagFromPeer) and are referenced by the freeform tag arrays+ // on ingredients, so we want the canonical rows present before the ingredient+ // rows land. They have no FK to scraps/ingredients, so ordering is otherwise+ // free. Each row in its own try/catch.+ for (const tag of envelope.tags || []) {+ try {+ const res = await upsertTagFromPeer(tag);+ if (!res.applied) stats.tags.skipped++;+ else if (res.isInsert) stats.tags.inserted++;+ else stats.tags.updated++;+ } catch (err) {+ stats.tags.failed++;+ recordFailure('tag', tag?.id, err);+ }+ }++ // Scraps next (sources FK to BOTH so we want the parents present before// the join rows land). Each row in its own try/catch — one malformed row// must NOT abort the rest of the envelope.for (const scrap of envelope.scraps || []) {diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.jsindex 4a645daf97..ffa4b5f5ec 100644--- a/server/services/catalogSync.test.js+++ b/server/services/catalogSync.test.js@@ -18,12 +18,14 @@ vi.mock('./catalogDB.js', () => ({getSourceChangesSince: vi.fn(),getRefChangesSince: vi.fn(),getRelationChangesSince: vi.fn(),+ getTagChangesSince: vi.fn(),getMaxSequences: vi.fn(),upsertScrapFromPeer: vi.fn(),upsertIngredientFromPeer: vi.fn(),upsertSourceFromPeer: vi.fn(),upsertRefFromPeer: vi.fn(),upsertRelationFromPeer: vi.fn(),+ upsertTagFromPeer: vi.fn(),}));vi.mock('../lib/schemaVersions.js', async () => {@@ -51,6 +53,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {catalogDB.upsertSourceFromPeer.mockResolvedValueOnce(undefined);catalogDB.upsertRefFromPeer.mockResolvedValueOnce(undefined);catalogDB.upsertRelationFromPeer.mockResolvedValueOnce(undefined);+ catalogDB.upsertTagFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });const stats = await applyRemoteChanges({scraps: [{ id: 's1', rawText: 'x', createdAt: 't', updatedAt: 't' }],@@ -61,6 +64,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {sources: [{ ingredientId: 'i1', scrapId: 's1', extractedAt: 't' }],refs: [{ ingredientId: 'i1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: 't' }],relations: [{ fromId: 'i1', toId: 'i2', kind: 'lives-in', createdAt: 't' }],+ tags: [{ id: 'cat-tag-noir', label: 'Noir', createdAt: 't', updatedAt: 't' }],});expect(stats.scraps.inserted).toBe(1);@@ -69,9 +73,29 @@ describe('applyRemoteChanges — dispatch + stats', () => {expect(stats.sources.applied).toBe(1);expect(stats.refs.applied).toBe(1);expect(stats.relations.applied).toBe(1);+ expect(stats.tags.inserted).toBe(1);expect(stats.errors).toHaveLength(0);});+ it('counts tag inserts / updates / skips and isolates a failing tag row', async () => {+ catalogDB.upsertTagFromPeer.mockResolvedValueOnce({ applied: true, isInsert: false }); // LWW update+ catalogDB.upsertTagFromPeer.mockResolvedValueOnce({ applied: false }); // LWW skip+ catalogDB.upsertTagFromPeer.mockRejectedValueOnce(new Error('bad tag'));++ const stats = await applyRemoteChanges({+ tags: [+ { id: 'cat-tag-noir', label: 'Noir', createdAt: 't', updatedAt: 't2' },+ { id: 'cat-tag-pulp', label: 'Pulp', createdAt: 't', updatedAt: 't' },+ { id: 'cat-tag-bad', label: 'Bad', createdAt: 't', updatedAt: 't' },+ ],+ });++ expect(stats.tags.updated).toBe(1);+ expect(stats.tags.skipped).toBe(1);+ expect(stats.tags.failed).toBe(1);+ expect(stats.errors[0]).toMatchObject({ kind: 'tag', id: 'cat-tag-bad', message: 'bad tag' });+ });+it('isolates a failing relation row and records it', async () => {catalogDB.upsertRelationFromPeer.mockRejectedValueOnce(new Error('fk violation'));const stats = await applyRemoteChanges({@@ -117,6 +141,10 @@ describe('applyRemoteChanges — dispatch + stats', () => {catalogDB.upsertRelationFromPeer.mockImplementation(async () => {order.push('relation');});+ catalogDB.upsertTagFromPeer.mockImplementation(async () => {+ order.push('tag');+ return { applied: true, isInsert: true };+ });await applyRemoteChanges({relations: [{ fromId: 'i1', toId: 'i2', kind: 'lives-in', createdAt: 't' }],@@ -124,11 +152,13 @@ describe('applyRemoteChanges — dispatch + stats', () => {sources: [{ ingredientId: 'i1', scrapId: 's1', extractedAt: 't' }],ingredients: [{ id: 'i1', type: 'character', name: 'A', createdAt: 't', updatedAt: 't' }],scraps: [{ id: 's1', rawText: 'x', createdAt: 't', updatedAt: 't' }],+ tags: [{ id: 'cat-tag-noir', label: 'Noir', createdAt: 't', updatedAt: 't' }],});- // Relations land last so both FK ends are present from the ingredient- // upserts.- expect(order).toEqual(['scrap', 'ingredient', 'source', 'ref', 'relation']);+ // Tags land FIRST (canonical rows present before the ingredient tag arrays+ // reference them); relations land last so both FK ends are present from the+ // ingredient upserts.+ expect(order).toEqual(['tag', 'scrap', 'ingredient', 'source', 'ref', 'relation']);});});@@ -178,33 +208,37 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {catalogDB.getSourceChangesSince.mockResolvedValue({ items: [], hasMore: false });catalogDB.getRefChangesSince.mockResolvedValue({ items: [], hasMore: false });catalogDB.getRelationChangesSince.mockResolvedValue({ items: [], hasMore: false });+ catalogDB.getTagChangesSince.mockResolvedValue({ items: [], hasMore: false });});- it('accepts a scalar since and applies it uniformly to all five kinds', async () => {+ it('accepts a scalar since and applies it uniformly to all six kinds', async () => {await getChangesSince('42', 100);expect(catalogDB.getScrapChangesSince).toHaveBeenCalledWith('42', 100);expect(catalogDB.getIngredientChangesSince).toHaveBeenCalledWith('42', 100);expect(catalogDB.getSourceChangesSince).toHaveBeenCalledWith('42', 100);expect(catalogDB.getRefChangesSince).toHaveBeenCalledWith('42', 100);expect(catalogDB.getRelationChangesSince).toHaveBeenCalledWith('42', 100);+ expect(catalogDB.getTagChangesSince).toHaveBeenCalledWith('42', 100);});it('accepts a per-kind cursor object', async () => {- await getChangesSince({ scraps: '5', ingredients: '10', sources: '15', refs: '20', relations: '25' }, 100);+ await getChangesSince({ scraps: '5', ingredients: '10', sources: '15', refs: '20', relations: '25', tags: '30' }, 100);expect(catalogDB.getScrapChangesSince).toHaveBeenCalledWith('5', 100);expect(catalogDB.getIngredientChangesSince).toHaveBeenCalledWith('10', 100);expect(catalogDB.getSourceChangesSince).toHaveBeenCalledWith('15', 100);expect(catalogDB.getRefChangesSince).toHaveBeenCalledWith('20', 100);expect(catalogDB.getRelationChangesSince).toHaveBeenCalledWith('25', 100);+ expect(catalogDB.getTagChangesSince).toHaveBeenCalledWith('30', 100);});it('rejects non-numeric cursor values, falling back to "0"', async () => {- await getChangesSince({ scraps: '5', ingredients: 'NaN', sources: null, refs: undefined, relations: 'x' }, 100);+ await getChangesSince({ scraps: '5', ingredients: 'NaN', sources: null, refs: undefined, relations: 'x', tags: 'y' }, 100);expect(catalogDB.getScrapChangesSince).toHaveBeenCalledWith('5', 100);expect(catalogDB.getIngredientChangesSince).toHaveBeenCalledWith('0', 100);expect(catalogDB.getSourceChangesSince).toHaveBeenCalledWith('0', 100);expect(catalogDB.getRefChangesSince).toHaveBeenCalledWith('0', 100);expect(catalogDB.getRelationChangesSince).toHaveBeenCalledWith('0', 100);+ expect(catalogDB.getTagChangesSince).toHaveBeenCalledWith('0', 100);});it('per-kind maxSequence falls back to the inbound cursor on quiet kinds', async () => {@@ -214,7 +248,7 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {});catalogDB.getIngredientChangesSince.mockResolvedValue({ items: [], hasMore: false });- const res = await getChangesSince({ scraps: '50', ingredients: '99', sources: '88', refs: '77', relations: '66' }, 100);+ const res = await getChangesSince({ scraps: '50', ingredients: '99', sources: '88', refs: '77', relations: '66', tags: '55' }, 100);// Quiet kinds reflect the inbound cursor — NOT 0 — so the next pull// doesn't move backward.@@ -223,6 +257,21 @@ describe('getChangesSince — cursor normalization + per-kind advance', () => {expect(res.maxSequences.sources).toBe('88');expect(res.maxSequences.refs).toBe('77');expect(res.maxSequences.relations).toBe('66');+ expect(res.maxSequences.tags).toBe('55');+ });++ it('advances the tags cursor to the last tag row + hasMore when only tags report more', async () => {+ catalogDB.getTagChangesSince.mockResolvedValue({+ items: [+ { id: 'cat-tag-noir', label: 'Noir', syncSequence: '7' },+ { id: 'cat-tag-pulp', label: 'Pulp', syncSequence: '8' },+ ],+ hasMore: true,+ });+ const res = await getChangesSince({ scraps: '0', ingredients: '0', sources: '0', refs: '0', relations: '0', tags: '0' }, 100);+ expect(res.tags).toHaveLength(2);+ expect(res.maxSequences.tags).toBe('8');+ expect(res.hasMore).toBe(true);});it('advances the relations cursor to the last relation row', async () => {