Skip to content

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

make catalog color palette / stats / aliases editable; fix stat shape mismatch

[._.]/ Adam Eivyafb2f8e6a91e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f07098dfae..956cfc6b09 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,8 @@
## Added
+- **[catalog-character-sheet-enrichment] Catalog and Universe Builder are now the same durable record, and the catalog's color palette / stats / aliases are editable inline.** Editing a character/place/object on the Catalog detail page and editing it on the Universe Builder canon surface used to write two parallel copies (the `catalog_ingredients` row and the embedded `universe.characters[]` entry) that silently drifted apart. They're now kept in lockstep by a bidirectional projection (`server/services/catalogCanonProjection.js`): a Catalog edit fans into every linked universe's embedded canon entry (best-effort, after the response), and a canon edit projects back into the catalog row synchronously inside `updateUniverse` so the embedded copy is a never-lagging cache of the one store of record. Conflicts resolve last-writer-wins on `updatedAt`; an in-flight re-entrancy guard breaks the catalog→canon→catalog loop so each side is written exactly once per edit. A one-time boot reconciliation (`reconcileCanonCatalog.js`, marker `data/catalog-canon-reconcile.applied.json`, registered as migration `054`) collapses any pre-existing divergence on first upgrade. Separately, the catalog character/place/object detail page now edits the enriched array fields inline — Aliases (string chips), Color Palette (`{ name, hex, role }` swatch rows with a native color picker), and Stats (`{ label, value }` rows) — instead of rendering them read-only; add-buttons disable at the storyBible caps (12 colors, 30 stats, 12 aliases). Bible-type payloads are now run through their storyBible sanitizer (`sanitizeCharacter`/`sanitizePlace`/`sanitizeObject`) on every catalog create/update so the array editors can't land malformed rows; idea/scene/concept and user-defined types are untouched. (Builds on the editable grouped sheet + reference-sheet panel + friendly-tag repair that shipped earlier as a slice.)
+
- **[catalog-user-defined-types] Define your own Catalog ingredient types in Settings → Catalog.** The catalog shipped six built-in types (character / place / object / idea / scene / concept); you can now add your own — wardrobe, vehicle, faction, magic-system, prompt-fragment, anything — without a code change. A new Settings → Catalog tab lists the built-ins read-only and lets you build custom types from a flat field list: each type is `{ id, label, primaryContentKey, fields: [{ key, label, kind: 'string' | 'longtext' | 'tags' | 'ref', maxLength? }] }`. User types persist in `data/settings.json` (`catalogUserTypes`) — not a new table — and merge into the active type registry at boot and on every save, so they show up immediately as filter chips, in the "New" dropdown, and as a fully editable detail page driven by a single generic field renderer (no per-type React file). A `ref` field links to another catalog ingredient via the existing picker; `tags` reuses the tag chip input. Validity is enforced at the app layer (the registry + a Zod refinement on the ingredient `type`), building on the already-dropped DB `CHECK`. User types federate: they ride a new additive `catalogTypes` block in the catalog sync envelope (LWW-merged into each peer's own settings slice, skipping built-in-id collisions), gated by `PORTOS_SCHEMA_VERSIONS.catalog` bumped to 8 — a peer on an older catalog schema rejects a forward-shaped push with a clean 412 rather than dropping the definitions and then choking on ingredients of an unknown type. Deleting a type that still has ingredients is refused unless you force it (the orphaned rows survive under a fallback editor). No DB migration — settings-only.
- **[catalog-scrap-chunking] Long scrap pastes are now chunked so extraction doesn't silently degrade.** Pasting (or ingesting via URL / file / voice) a very long scrap — a whole screenplay, a 50k-word manuscript — used to land as a single row and a single LLM extraction pass, quietly overflowing the model's context and dropping ingredients from the tail. Inputs over ~12k characters now split into a parent row plus N child chunks (preferring paragraph, then sentence, then word boundaries so nothing is cut mid-word and the text reassembles exactly); the extractor runs each chunk independently (two at a time) and unions the results, de-duplicating by name + type so the same character mentioned in three chunks appears once. Short pastes behave exactly as before — one row, one pass. The chunk parent/child structure federates to peers (the catalog sync wire version is bumped, so a peer on an older catalog schema declines a forward-shaped push cleanly rather than mis-applying it); existing scraps are left as-is.
@@ -50,6 +52,7 @@
## Fixed
+- **[catalog-character-sheet-enrichment] Catalog character stats now display.** The catalog detail page's read-only stats list read each stat's `.key` field, but the storyBible canon shape stores stats as `{ label, value }` — so every stat rendered with a blank label. The new editable stat editor and the read path both standardize on `.label`, so stats finally show (and edit) correctly.
- **[browser-navigate-ssrf-guard] SSRF guard on the browser navigate route.** `POST /api/browser/navigate` validated its URL with a bare `z.string().url()`, so `file://`, loopback, link-local, and cloud-metadata (`169.254.169.254`) targets were reachable — a redirect or agent-driven navigation could turn it into local-file exfiltration or a metadata-endpoint hit. It now reuses the catalog ingest guard (`isSafeIngestUrl`): http(s) only, with loopback / link-local / metadata hosts blocked (including IPv4-mapped-IPv6 bypass forms like `[::ffff:127.0.0.1]`). Private/LAN and Tailscale hosts stay allowed; `localhost`/`127.x` are now blocked, so navigate a local app by its LAN IP/hostname. Bad input also returns a clean 400 instead of a 500. The shared host guard was also hardened against two literal bypasses (deprecated IPv4-compatible IPv6 like `[::127.0.0.1]`, and trailing-FQDN-dot hosts like `localhost.`), which strengthens catalog URL ingest as well.
- **[catalog round-trip + cast multi-role] Catalog export → re-import keeps ref links, scraps, and non-primary payload keys; Cast unlink is role-precise.** Re-importing a JSON export bundle through Bulk Import now recreates the bundle's slice membership: the parser carries the bundle's own `ref` plus each row's `roleForExportedRef`, and the route falls back to them when no explicit `defaults.*Ref` override is supplied — so a re-imported slice is no longer invisible to "Appears in" and to future slice exports. The markdown parser now recognizes the ` ```json ` payload fence and the `### Scraps` subsection as body terminators and round-trips them into `payload.*` / a sibling `scraps[]` instead of polluting the primary description/summary with fence text. The Cast (from Catalog) panel's unlink now removes only the `(ingredient, role)` row that was unlinked, not every row sharing the ingredient id — correct when the same ingredient is linked to one record under multiple roles.
- Custom browser setup is more reliable: macOS app bundles are paired automatically with Chrome-compatible browser paths, Canary setup no longer repeatedly prompts after you decline, and non-interactive updates no longer risk hanging on package-manager password prompts.
diff --git a/PLAN.md b/PLAN.md
index 6c313f32fc..4bd28476fb 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -12,7 +12,6 @@ _Merged 2026-05-30 (7 PRs, claude+codex reviewed): 15 items shipped to main —
_Re-triaged then cleared 2026-05-30 (post-merge follow-up pass): the 6 review-surfaced follow-ups + the 4 previously-gated items were each verified against `main` and all shipped — `catalog-bulk-import-scrap-persistence`, `catalog-sync-apply-kind-helper`, `catalog-detail-batched-endpoint`, `browser-navigate-ssrf-guard`, `catalog-bulk-import-route-db-tests`, `catalog-friendlify-universe-tags-on-sync`, the character-sheet slice, `catalog-type-table-vs-check`, and `catalog-ask-retrieval`. Still open below (verified still-valid 2026-05-30): `catalog-character-sheet-enrichment` (deep durable-record unification + structured array-field editors remain), `catalog-user-defined-types` (precondition now resolved; deferred until deliberately picked up), and `catalog-scrap-chunking` (per its own "wait for user pain" note — confirmed still not triggered)._
-- [ ] [catalog-character-sheet-enrichment] **Upgrade `client/src/pages/CatalogIngredient.jsx` character detail/edit routes (for example `/catalog/character/cat-chr-224496f9-22ec-4784-b84a-f69cecdd4f01`) into a full editable DnD-style character sheet backed by the enriched universe-canon payload.** Character rows should expose and edit all enriched canon data already present in universe records: identity, role/archetype, appearance, personality, goals/fears, relationships, stats/abilities, color palette, style notes, prompt/render hints, reference images, and any future `payload.schemaVersion` fields. If a character reference sheet has already been rendered, show it in the detail page; if none exists, allow rendering one from this page using the linked universe's style data (`styleNotes`, `influences`, `styleImageRefs`, palette, and render settings) when the ingredient has an associated universe ref. Catalog ingredients and universe canon characters must become the same durable records rather than copy-on-write mirrors: editing either the Catalog detail page or the universe canon surface should update the same `catalog_ingredients` row (with the universe canon entry carrying only a stable `ingredientId`/projection cache if needed), so enriched fields cannot diverge between Catalog and Universe Builder. Migration/backfill: update universe-backfilled character tags from machine tags like `from-universe, universe:14590a09-5a49-4994-b401-395ee354528d` to friendly, user-facing universe-name tags while preserving a structured universe ref for querying; ship a one-time data repair for the current instance as part of the implementation. Pairs with `[catalog-universe-builder-picker]`, `[catalog-bundled-universe-push]`, `[catalog-ingredient-media-refs]`, and `[catalog-payload-schemaversion-per-type]`. _In review 2026-05-30 (#560): SLICE shipped — the editable grouped character/place/object sheet (registry-driven `editorSections`/`editorFields`, scalar fields keyed to mirror `sanitizeCharacter` so edits land in the same `catalog_ingredients` row the canon reads), the "Reference sheet" panel, and the friendly-universe-tag data repair (`repairUniverseTags.js`, marker `053`). REMAINING: the deep durable-record unification (collapse the embedded universe-canon entry to a pure `ingredientId` projection so the catalog row is the single store of record) and the structured array-field editors (color palette / stats / aliases, currently read-only here). Keep this item open until those land._
### Creative Catalog — extensibility roadmap
diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.js
index 7da31dad77..b6dedd5fd8 100644
--- a/client/src/lib/catalogTypes.js
+++ b/client/src/lib/catalogTypes.js
@@ -159,6 +159,25 @@ export const CHARACTER_LIST_FIELDS = Object.freeze([
{ key: 'stats', label: 'Stats', kind: 'kv' },
]);
+// Structured array-field editors for the bible types — client MIRROR of the
+// server `editableListFields` (server/lib/catalogTypes.js). The Catalog detail
+// editor renders these as inline structured editors (AliasListEditor /
+// ColorPaletteEditor / StatListEditor) instead of read-only chips. The numeric
+// caps are hardcoded BIBLE_LIMITS values (the client can't import storyBible) —
+// the parity test asserts they match the server's BIBLE_LIMITS-sourced values
+// EXACTLY, so a limit bump on the server fails CI here until it's mirrored.
+// ALIAS_MAX=100, ALIASES_PER_ENTRY_MAX=12, COLOR_NAME_MAX=80,
+// COLORS_PER_PALETTE_MAX=12, STAT_VALUE_MAX=200, STATS_PER_CHARACTER_MAX=30
+const CHARACTER_EDITABLE_LIST_FIELDS = [
+ { key: 'aliases', label: 'Aliases', kind: 'stringArray', itemMax: 100, listMax: 12 },
+ { key: 'colorPalette', label: 'Color Palette', kind: 'colorPalette', itemMax: 80, listMax: 12 },
+ { key: 'stats', label: 'Stats', kind: 'kv', itemMax: 200, listMax: 30 },
+];
+const PLACE_EDITABLE_LIST_FIELDS = [];
+const OBJECT_EDITABLE_LIST_FIELDS = [
+ { key: 'aliases', label: 'Aliases', kind: 'stringArray', itemMax: 100, listMax: 12 },
+];
+
export const CATALOG_TYPES = Object.freeze([
{
id: 'character',
@@ -173,6 +192,7 @@ export const CATALOG_TYPES = Object.freeze([
// reads. `editorFields` is the flattened enumeration of these same keys.
editorSections: CHARACTER_SECTIONS,
editorFields: flattenSections(CHARACTER_SECTIONS),
+ editableListFields: CHARACTER_EDITABLE_LIST_FIELDS,
},
{
id: 'place',
@@ -183,6 +203,7 @@ export const CATALOG_TYPES = Object.freeze([
snippetFallbackKeys: ['description', 'summary', 'significance', 'notes'],
editorSections: PLACE_SECTIONS,
editorFields: flattenSections(PLACE_SECTIONS),
+ editableListFields: PLACE_EDITABLE_LIST_FIELDS,
},
{
id: 'object',
@@ -193,6 +214,7 @@ export const CATALOG_TYPES = Object.freeze([
snippetFallbackKeys: ['description', 'significance', 'summary', 'notes'],
editorSections: OBJECT_SECTIONS,
editorFields: flattenSections(OBJECT_SECTIONS),
+ editableListFields: OBJECT_EDITABLE_LIST_FIELDS,
},
{
id: 'idea',
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 20d86a59a7..6cba4d16e8 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -28,7 +28,7 @@ import IngredientPicker from '../components/IngredientPicker';
import MediaImage from '../components/MediaImage';
import TagPicker from '../components/TagPicker';
import GenericIngredientFields from '../components/GenericIngredientFields';
-import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind, CHARACTER_LIST_FIELDS } from '../lib/catalogTypes';
+import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';
import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';
import { timeAgo } from '../utils/formatters';
@@ -381,11 +381,12 @@ export default function CatalogIngredient() {
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} />
+ {/* Structured array-field editors (aliases / color palette / stats).
+ Driven by the type's registry-declared `editableListFields`; the
+ same durable catalog row the Universe Builder canon surface edits.
+ Light/user types declare none and skip this entirely. */}
+ {!isUserType && Array.isArray(typeDef.editableListFields) && typeDef.editableListFields.length > 0 && (
+ <EditableListFields fields={typeDef.editableListFields} payload={payload} onChange={updatePayload} />
)}
</div>
@@ -465,53 +466,161 @@ function SheetSection({ title, fields, payload, onChange }) {
);
}
-// 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;
+// Structured array-field editors (aliases / color palette / stats). Each field
+// is declared on the type registry as `{ key, label, kind, itemMax, listMax }`
+// and dispatched to the matching editor below. Edits write the WHOLE array back
+// through `onChange(key, nextArray)` into the shared payload state, so the
+// page's existing `handleSave` persists them — no new endpoint. The server's
+// storyBible sanitizer re-caps/normalizes on save (it owns the durable shape);
+// these editors mirror its caps so the add-button disables at the limit rather
+// than silently dropping rows on save.
+function EditableListFields({ fields, payload, onChange }) {
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 className="space-y-4 pt-1">
+ {fields.map((f) => {
+ const value = Array.isArray(payload[f.key]) ? payload[f.key] : [];
+ const set = (next) => onChange(f.key, next);
+ if (f.kind === 'colorPalette') {
+ return <ColorPaletteEditor key={f.key} field={f} value={value} onChange={set} />;
+ }
+ if (f.kind === 'kv') {
+ return <StatListEditor key={f.key} field={f} value={value} onChange={set} />;
+ }
+ return <AliasListEditor key={f.key} field={f} value={value} onChange={set} />;
+ })}
+ </div>
+ );
+}
+
+// Shared section header for the array editors. `atCap` toggles the add-button
+// disabled state + a small "(max N)" hint so the cap is discoverable.
+function ListEditorHeader({ label, count, listMax, onAdd, addLabel = 'Add' }) {
+ const atCap = count >= listMax;
+ return (
+ <div className="flex items-center justify-between gap-2 mb-1.5">
+ <span className="text-xs uppercase tracking-wider text-gray-500">
+ {label} <span className="text-gray-600 normal-case tracking-normal">({count}/{listMax})</span>
+ </span>
+ <button type="button" onClick={onAdd} disabled={atCap}
+ className="inline-flex items-center gap-1 text-[11px] px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-40 disabled:cursor-not-allowed"
+ title={atCap ? `Maximum ${listMax} reached` : addLabel}>
+ <Plus size={12} aria-hidden="true" /> {addLabel}
+ </button>
+ </div>
+ );
+}
+
+const listInput = 'px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs focus:outline-none focus:border-port-accent';
+
+// String-array chips editor (e.g. aliases). Each row is a single-line input
+// with a remove button; the add-button is disabled at `listMax`.
+function AliasListEditor({ field, value, onChange }) {
+ const { label, itemMax, listMax } = field;
+ const items = value.map((v) => (typeof v === 'string' ? v : String(v ?? '')));
+ const add = () => { if (items.length < listMax) onChange([...items, '']); };
+ const update = (i, next) => onChange(items.map((v, idx) => (idx === i ? next : v)));
+ const remove = (i) => onChange(items.filter((_, idx) => idx !== i));
+ return (
+ <div>
+ <ListEditorHeader label={label} count={items.length} listMax={listMax} onAdd={add} addLabel="Add alias" />
+ {items.length === 0 ? (
+ <p className="text-[11px] text-gray-600">None yet.</p>
+ ) : (
+ <div className="flex flex-wrap gap-1.5">
+ {items.map((v, i) => {
+ const inputId = `${field.key}-${i}`;
+ return (
+ <span key={i} className="inline-flex items-center gap-1">
+ <label htmlFor={inputId} className="sr-only">{label} {i + 1}</label>
+ <input id={inputId} type="text" value={v} maxLength={itemMax}
+ onChange={(e) => update(i, e.target.value)} className={`${listInput} w-40`} />
+ <button type="button" onClick={() => remove(i)} aria-label={`Remove ${label} ${i + 1}`}
+ className="text-gray-500 hover:text-port-error"><X size={12} aria-hidden="true" /></button>
+ </span>
+ );
+ })}
</div>
- ))}
+ )}
+ </div>
+ );
+}
+
+// Color-palette editor — rows of `{ name, hex, role }`. A native color swatch
+// sits beside the hex text input so the user can pick OR type a value (the
+// sanitizer tolerates non-hex names like "off-white", so the text input is the
+// source of truth and the swatch is a convenience).
+function ColorPaletteEditor({ field, value, onChange }) {
+ const { label, listMax } = field;
+ const rows = value.map((c) => (c && typeof c === 'object' ? c : {}));
+ const add = () => { if (rows.length < listMax) onChange([...rows, { name: '', hex: '', role: '' }]); };
+ const update = (i, key, next) => onChange(rows.map((c, idx) => (idx === i ? { ...c, [key]: next } : c)));
+ const remove = (i) => onChange(rows.filter((_, idx) => idx !== i));
+ // A native <input type=color> needs a 7-char #rrggbb; a blank/short/named
+ // value falls back to a neutral swatch so the picker doesn't error.
+ const swatchVal = (hex) => (/^#[0-9a-fA-F]{6}$/.test(hex || '') ? hex : '#888888');
+ return (
+ <div>
+ <ListEditorHeader label={label} count={rows.length} listMax={listMax} onAdd={add} addLabel="Add color" />
+ {rows.length === 0 ? (
+ <p className="text-[11px] text-gray-600">None yet.</p>
+ ) : (
+ <ul className="space-y-1.5">
+ {rows.map((c, i) => (
+ <li key={i} className="flex items-center gap-1.5 flex-wrap">
+ <label htmlFor={`${field.key}-hex-${i}`} className="sr-only">{label} {i + 1} hex</label>
+ <input type="color" aria-label={`${label} ${i + 1} swatch`} value={swatchVal(c.hex)}
+ onChange={(e) => update(i, 'hex', e.target.value)}
+ className="w-7 h-7 rounded border border-port-border bg-port-bg p-0.5 cursor-pointer" />
+ <input type="text" placeholder="name" value={c.name || ''} maxLength={80}
+ aria-label={`${label} ${i + 1} name`}
+ onChange={(e) => update(i, 'name', e.target.value)} className={`${listInput} w-32`} />
+ <input id={`${field.key}-hex-${i}`} type="text" placeholder="#hex / value" value={c.hex || ''} maxLength={10}
+ onChange={(e) => update(i, 'hex', e.target.value)} className={`${listInput} w-28 font-mono`} />
+ <input type="text" placeholder="role (e.g. skin)" value={c.role || ''} maxLength={120}
+ aria-label={`${label} ${i + 1} role`}
+ onChange={(e) => update(i, 'role', e.target.value)} className={`${listInput} w-32`} />
+ <button type="button" onClick={() => remove(i)} aria-label={`Remove ${label} ${i + 1}`}
+ className="text-gray-500 hover:text-port-error"><X size={12} aria-hidden="true" /></button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
+
+// Key/value stat editor — rows of `{ label, value }`. NOTE the field shape: the
+// storyBible sanitizer (`sanitizeStat`) stores `{ label, value }`, NOT
+// `{ key, value }`. The prior read-only renderer read `s.key`, which silently
+// rendered blank for every real stat — this editor + the durable shape now
+// standardize on `.label`.
+function StatListEditor({ field, value, onChange }) {
+ const { label, itemMax, listMax } = field;
+ const rows = value.map((s) => (s && typeof s === 'object' ? s : {}));
+ const add = () => { if (rows.length < listMax) onChange([...rows, { label: '', value: '' }]); };
+ const update = (i, key, next) => onChange(rows.map((s, idx) => (idx === i ? { ...s, [key]: next } : s)));
+ const remove = (i) => onChange(rows.filter((_, idx) => idx !== i));
+ return (
+ <div>
+ <ListEditorHeader label={label} count={rows.length} listMax={listMax} onAdd={add} addLabel="Add stat" />
+ {rows.length === 0 ? (
+ <p className="text-[11px] text-gray-600">None yet.</p>
+ ) : (
+ <ul className="space-y-1.5">
+ {rows.map((s, i) => (
+ <li key={i} className="flex items-center gap-1.5 flex-wrap">
+ <label htmlFor={`${field.key}-label-${i}`} className="sr-only">{label} {i + 1} label</label>
+ <input id={`${field.key}-label-${i}`} type="text" placeholder="label" value={s.label || ''} maxLength={80}
+ onChange={(e) => update(i, 'label', e.target.value)} className={`${listInput} w-36`} />
+ <label htmlFor={`${field.key}-value-${i}`} className="sr-only">{label} {i + 1} value</label>
+ <input id={`${field.key}-value-${i}`} type="text" placeholder="value" value={s.value || ''} maxLength={itemMax}
+ onChange={(e) => update(i, 'value', e.target.value)} className={`${listInput} w-40`} />
+ <button type="button" onClick={() => remove(i)} aria-label={`Remove ${label} ${i + 1}`}
+ className="text-gray-500 hover:text-port-error"><X size={12} aria-hidden="true" /></button>
+ </li>
+ ))}
+ </ul>
+ )}
</div>
);
}
diff --git a/client/src/pages/CatalogIngredient.test.jsx b/client/src/pages/CatalogIngredient.test.jsx
index 1282b335eb..c2434dfd7f 100644
--- a/client/src/pages/CatalogIngredient.test.jsx
+++ b/client/src/pages/CatalogIngredient.test.jsx
@@ -32,7 +32,9 @@ const { CHAR_FIXTURE } = vi.hoisted(() => ({
motivations: 'Decode the machine.',
dislikes: 'Being underestimated.',
colorPalette: [{ name: 'Brass', hex: '#b08d57' }],
- stats: [{ key: 'Logic', value: '9' }],
+ // storyBible stats are { label, value } — the editor + durable shape
+ // standardize on .label (the prior read-only renderer wrongly read .key).
+ stats: [{ label: 'Logic', value: '9' }],
aliases: ['The Countess'],
},
refs: [{ refKind: 'universe', refId: 'u-1', refName: 'My Cool Universe', role: 'canon-character' }],
@@ -97,12 +99,51 @@ describe('CatalogIngredient — character sheet', () => {
expect(screen.getByDisplayValue('Being underestimated.')).toBeTruthy();
});
- it('renders read-only canon arrays (color palette + stats)', async () => {
+ it('renders EDITABLE array editors (color palette + stats + aliases) seeded from payload', 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();
+ await waitFor(() => expect(screen.getByRole("button", { name: /Add color/i })).toBeTruthy());
+ // Editors render their values as inputs now (editable), not static text.
+ expect(screen.getByDisplayValue('Brass')).toBeTruthy();
+ expect(screen.getByDisplayValue('Logic')).toBeTruthy(); // stat .label
+ expect(screen.getByDisplayValue('9')).toBeTruthy(); // stat .value
+ expect(screen.getByDisplayValue('The Countess')).toBeTruthy(); // alias
+ });
+
+ it('adds an alias chip, a palette swatch, and a stat row, then Save sends them in the payload', async () => {
+ const { updateCatalogIngredient } = await import('../services/apiCatalog');
+ updateCatalogIngredient.mockResolvedValue({ ...CHAR_FIXTURE, name: 'Ada Lovelace' });
+ renderPage();
+ await waitFor(() => expect(screen.getByRole("button", { name: /Add color/i })).toBeTruthy());
+
+ // Add one of each list type.
+ fireEvent.click(screen.getByRole('button', { name: /Add alias/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Add color/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Add stat/i }));
+
+ // Fill the newly-added rows. The new alias input is the empty one (index 1).
+ const aliasInputs = screen.getAllByLabelText(/^Aliases \d+$/);
+ fireEvent.change(aliasInputs[aliasInputs.length - 1], { target: { value: 'Lady Byron' } });
+ // New palette name input (empty) — last "Color Palette N name".
+ const paletteNames = screen.getAllByLabelText(/Color Palette \d+ name/);
+ fireEvent.change(paletteNames[paletteNames.length - 1], { target: { value: 'Cobalt' } });
+ const paletteHexes = screen.getAllByLabelText(/Color Palette \d+ hex/);
+ fireEvent.change(paletteHexes[paletteHexes.length - 1], { target: { value: '#0047ab' } });
+ // New stat label/value inputs (the empty pair).
+ const statLabels = screen.getAllByLabelText(/Stats \d+ label/);
+ fireEvent.change(statLabels[statLabels.length - 1], { target: { value: 'Charisma' } });
+ const statValues = screen.getAllByLabelText(/Stats \d+ value/);
+ fireEvent.change(statValues[statValues.length - 1], { target: { value: '7' } });
+
+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
+
+ await waitFor(() => expect(updateCatalogIngredient).toHaveBeenCalled());
+ const [, patch] = updateCatalogIngredient.mock.calls[0];
+ // aliases array carries the original + the new one.
+ expect(patch.payload.aliases).toEqual(['The Countess', 'Lady Byron']);
+ // colorPalette carries the original + the new { name, hex } row.
+ expect(patch.payload.colorPalette).toContainEqual({ name: 'Cobalt', hex: '#0047ab', role: '' });
+ // stats carry the original + the new { label, value } row (NOT { key }).
+ expect(patch.payload.stats).toContainEqual({ label: 'Charisma', value: '7' });
});
it('shows a render-reference-sheet deep-link when none exists and a universe ref is present', async () => {
diff --git a/server/lib/catalogTypes.js b/server/lib/catalogTypes.js
index 3f13dac2a1..f2486dca35 100644
--- a/server/lib/catalogTypes.js
+++ b/server/lib/catalogTypes.js
@@ -32,6 +32,27 @@
import { BIBLE_LIMITS } from './storyBible.js';
+// Structured array-field editors for the bible types. Each entry declares a
+// payload array key the Catalog detail editor renders as an inline structured
+// editor (string-array chips / color-swatch rows / label-value rows) rather
+// than a read-only chip list. `kind` selects the editor widget:
+// 'stringArray' — AliasListEditor (string[] chips)
+// 'colorPalette' — ColorPaletteEditor ({ name, hex, role } swatch rows)
+// 'kv' — StatListEditor ({ label, value } rows)
+// `itemMax`/`listMax` are the per-item char cap + per-list count cap, sourced
+// from BIBLE_LIMITS so the editor's "disable add at cap" matches the storyBible
+// sanitizer's silent drop. MIRRORED to client/src/lib/catalogTypes.js verbatim
+// (the parity test asserts they don't drift).
+const CHARACTER_EDITABLE_LIST_FIELDS = [
+ { key: 'aliases', label: 'Aliases', kind: 'stringArray', itemMax: BIBLE_LIMITS.ALIAS_MAX, listMax: BIBLE_LIMITS.ALIASES_PER_ENTRY_MAX },
+ { key: 'colorPalette', label: 'Color Palette', kind: 'colorPalette', itemMax: BIBLE_LIMITS.COLOR_NAME_MAX, listMax: BIBLE_LIMITS.COLORS_PER_PALETTE_MAX },
+ { key: 'stats', label: 'Stats', kind: 'kv', itemMax: BIBLE_LIMITS.STAT_VALUE_MAX, listMax: BIBLE_LIMITS.STATS_PER_CHARACTER_MAX },
+];
+const PLACE_EDITABLE_LIST_FIELDS = [];
+const OBJECT_EDITABLE_LIST_FIELDS = [
+ { key: 'aliases', label: 'Aliases', kind: 'stringArray', itemMax: BIBLE_LIMITS.ALIAS_MAX, listMax: BIBLE_LIMITS.ALIASES_PER_ENTRY_MAX },
+];
+
/**
* One entry per ingredient type. Shape:
* id — catalog `type` discriminator (column value).
@@ -64,6 +85,7 @@ const REGISTRY = [
primaryContentLabel: 'Physical Description',
snippetFallbackKeys: ['physicalDescription', 'description', 'summary', 'personality', 'significance', 'role', 'notes'],
ftsFields: ['description', 'physicalDescription', 'personality', 'background', 'summary', 'notes', 'role', 'motivations', 'significance'],
+ editableListFields: CHARACTER_EDITABLE_LIST_FIELDS,
extractionShape: 'bible',
payloadSchemaVersion: 1,
payloadUpgraders: {},
@@ -78,6 +100,7 @@ const REGISTRY = [
primaryContentLabel: 'Description',
snippetFallbackKeys: ['description', 'summary', 'significance', 'notes'],
ftsFields: [],
+ editableListFields: PLACE_EDITABLE_LIST_FIELDS,
extractionShape: 'bible',
payloadSchemaVersion: 1,
payloadUpgraders: {},
@@ -92,6 +115,7 @@ const REGISTRY = [
primaryContentLabel: 'Description',
snippetFallbackKeys: ['description', 'significance', 'summary', 'notes'],
ftsFields: [],
+ editableListFields: OBJECT_EDITABLE_LIST_FIELDS,
extractionShape: 'bible',
payloadSchemaVersion: 1,
payloadUpgraders: {},
diff --git a/server/lib/catalogTypes.parity.test.js b/server/lib/catalogTypes.parity.test.js
index fbf1c8b003..f508d68f6b 100644
--- a/server/lib/catalogTypes.parity.test.js
+++ b/server/lib/catalogTypes.parity.test.js
@@ -30,7 +30,7 @@ import {
// The fields the client mirror MUST match the server on — the ones the UI
// reads. `ftsFields` / `extractionShape` / `payloadSchemaVersion` are
// server-only concerns and intentionally not mirrored.
-const MIRRORED_FIELDS = ['id', 'label', 'badgeColor', 'primaryContentKey', 'primaryContentLabel', 'snippetFallbackKeys'];
+const MIRRORED_FIELDS = ['id', 'label', 'badgeColor', 'primaryContentKey', 'primaryContentLabel', 'snippetFallbackKeys', 'editableListFields'];
describe('catalog type registry — server↔client parity', () => {
it('exposes the same type ids in the same order', () => {