Skip to content

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

feat(universe): add approved character production packages (#5390)

[._.]/ Adam Eivy331d04b5ee03
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsx
index 9a14155426..b713ce82a4 100644
--- a/client/src/components/universe/CharacterDetailEditor.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.jsx
@@ -10,10 +10,11 @@
* only knows the field shape.
*/
+import { useState } from 'react';
import {
Plus, Trash2, WandSparkles, Loader2,
Palette, Hand, Smile, Package, BookOpen, Eye, Activity, Users, Swords,
- Drama, KeyRound,
+ Drama, KeyRound, Mic, Images, BadgeCheck,
} from 'lucide-react';
import { BIBLE_LIMITS as L } from '../../lib/bibleLimits';
import useFieldDraft from '../../hooks/useFieldDraft';
@@ -82,6 +83,12 @@ const RELATIONSHIP_OPPOSITION_AXES = Object.freeze([
// the field. `''` = unset.
const CHARACTER_ARC_TYPES = Object.freeze(['positive', 'negative', 'flat']);
const SLIDER_AXES = Object.freeze(['proactivity', 'likability', 'competence']);
+const VOICE_SOURCE_POLICIES = Object.freeze(['designed', 'consented-performance', 'licensed']);
+const IDENTITY_ASSET_ROLES = Object.freeze([
+ 'neutral', 'profile', 'full-body', 'expression-gesture', 'wardrobe',
+ 'prop-scale', 'negative-identity',
+]);
+const REQUIRED_IDENTITY_ROLES = Object.freeze(['neutral', 'profile', 'full-body']);
const LIST_SECTIONS = Object.freeze([
{
@@ -593,6 +600,223 @@ function ArcFrameworkControls({ entry, onPatch, disabled, idPrefix }) {
);
}
+const splitProductionTerms = (value, max, itemMax) => value
+ .split(',')
+ .map((item) => item.trim().slice(0, itemMax))
+ .filter(Boolean)
+ .slice(0, max);
+
+function VoiceCanonPronunciationRow({ row, idx, onChange, onRemove, disabled }) {
+ const term = useFieldDraft(row.term || '', (value) => onChange({ term: value }));
+ const pronunciation = useFieldDraft(row.pronunciation || '', (value) => onChange({ pronunciation: value }));
+ return (
+ <div className="flex items-start gap-1.5">
+ <input
+ type="text" value={term.value} onChange={term.onChange} onBlur={term.onBlur}
+ maxLength={L.VOICE_CANON_PRONUNCIATION_TERM_MAX} placeholder="term"
+ disabled={disabled} aria-label={`pronunciation ${idx + 1} term`}
+ className={REL_SELECT_CLASS}
+ />
+ <input
+ type="text" value={pronunciation.value} onChange={pronunciation.onChange} onBlur={pronunciation.onBlur}
+ maxLength={L.VOICE_CANON_PRONUNCIATION_VALUE_MAX} placeholder="how it is said"
+ disabled={disabled} aria-label={`pronunciation ${idx + 1} pronunciation`}
+ className={REL_SELECT_CLASS}
+ />
+ <button
+ type="button" onClick={onRemove} disabled={disabled}
+ title="Remove pronunciation" aria-label={`remove pronunciation ${idx + 1}`}
+ className="shrink-0 text-gray-500 hover:text-port-error disabled:opacity-30"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ );
+}
+
+function VoiceCanonSection({ entry, onPatch, disabled }) {
+ const canon = entry.voiceCanon || {};
+ const [newPronunciation, setNewPronunciation] = useState({ term: '', pronunciation: '' });
+ const commit = (patch) => {
+ const approvalPatch = Object.hasOwn(patch, 'approved') ? {} : { approved: false };
+ onPatch?.({
+ voiceCanon: { version: 1, ...canon, ...patch, ...approvalPatch },
+ });
+ };
+ const description = useFieldDraft(canon.description || '', (value) => commit({ description: value }));
+ const delivery = useFieldDraft(canon.defaultDelivery || '', (value) => commit({ defaultDelivery: value }));
+ const emotionalRange = useFieldDraft((canon.emotionalRange || []).join(', '), (value) => commit({
+ emotionalRange: splitProductionTerms(value, L.VOICE_CANON_RANGE_MAX, L.VOICE_CANON_RANGE_ITEM_MAX),
+ }));
+ const avoid = useFieldDraft((canon.avoid || []).join(', '), (value) => commit({
+ avoid: splitProductionTerms(value, L.VOICE_CANON_AVOID_MAX, L.VOICE_CANON_AVOID_ITEM_MAX),
+ }));
+ const pronunciations = Array.isArray(canon.pronunciations) ? canon.pronunciations : [];
+ const newTerm = newPronunciation.term.trim();
+ const newValue = newPronunciation.pronunciation.trim();
+ const addPronunciation = () => {
+ if (!newTerm || !newValue) return;
+ commit({ pronunciations: [...pronunciations, { term: newTerm, pronunciation: newValue }] });
+ setNewPronunciation({ term: '', pronunciation: '' });
+ };
+ const approved = canon.approved === true;
+ return (
+ <BoxedSection icon={Mic} label="Voice canon" summary={approved ? `v${canon.version || 1} approved` : 'candidate'}>
+ <p className="text-[10px] leading-snug text-gray-500">
+ Portable performance direction only. Local profiles, recordings, providers, and model artifacts stay machine-local.
+ </p>
+ <div className="grid grid-cols-2 gap-1.5">
+ <div>
+ <label htmlFor={`voice-canon-version-${entry.id}`} className="block text-[10px] uppercase tracking-wider text-gray-500">Revision</label>
+ <input
+ id={`voice-canon-version-${entry.id}`} type="number" min="1" max={L.VOICE_CANON_VERSION_MAX}
+ value={canon.version || 1} onChange={(e) => commit({ version: Number(e.target.value) || 1 })}
+ disabled={disabled} className={REL_INPUT_CLASS}
+ />
+ </div>
+ <div>
+ <label htmlFor={`voice-canon-source-${entry.id}`} className="block text-[10px] uppercase tracking-wider text-gray-500">Source policy</label>
+ <select
+ id={`voice-canon-source-${entry.id}`} value={canon.sourcePolicy || ''}
+ onChange={(e) => commit({ sourcePolicy: e.target.value || null })} disabled={disabled}
+ className={REL_INPUT_CLASS}
+ >
+ <option value="">— unset —</option>
+ {VOICE_SOURCE_POLICIES.map((policy) => <option key={policy} value={policy}>{policy}</option>)}
+ </select>
+ </div>
+ </div>
+ <label className="flex items-center gap-1.5 text-[11px] text-gray-300">
+ <input type="checkbox" checked={approved} onChange={(e) => commit({ approved: e.target.checked })} disabled={disabled} />
+ <BadgeCheck size={12} className={approved ? 'text-port-success' : 'text-gray-500'} />
+ {approved ? 'Approved revision' : 'Candidate revision'}
+ </label>
+ <textarea
+ value={description.value} onChange={description.onChange} onBlur={description.onBlur}
+ placeholder="Voice description: timbre, texture, breath, and register"
+ maxLength={L.VOICE_CANON_DESCRIPTION_MAX} disabled={disabled} rows={2}
+ aria-label="voice canon description" className={REL_INPUT_CLASS}
+ />
+ <textarea
+ value={delivery.value} onChange={delivery.onChange} onBlur={delivery.onBlur}
+ placeholder="Default delivery: pacing, pauses, energy, and distance"
+ maxLength={L.VOICE_CANON_DELIVERY_MAX} disabled={disabled} rows={2}
+ aria-label="voice canon default delivery" className={REL_INPUT_CLASS}
+ />
+ <input
+ type="text" value={emotionalRange.value} onChange={emotionalRange.onChange} onBlur={emotionalRange.onBlur}
+ placeholder="Emotional range, comma-separated" maxLength={L.VOICE_CANON_RANGE_MAX * L.VOICE_CANON_RANGE_ITEM_MAX}
+ disabled={disabled} aria-label="voice canon emotional range" className={REL_INPUT_CLASS}
+ />
+ <input
+ type="text" value={avoid.value} onChange={avoid.onChange} onBlur={avoid.onBlur}
+ placeholder="Avoid in delivery, comma-separated" maxLength={L.VOICE_CANON_AVOID_MAX * L.VOICE_CANON_AVOID_ITEM_MAX}
+ disabled={disabled} aria-label="voice canon avoid" className={REL_INPUT_CLASS}
+ />
+ <div className="space-y-1">
+ <span className="block text-[10px] uppercase tracking-wider text-gray-500">Pronunciations</span>
+ {pronunciations.map((row, idx) => (
+ <VoiceCanonPronunciationRow
+ key={idx} row={row} idx={idx} disabled={disabled}
+ onChange={(patch) => commit({ pronunciations: pronunciations.map((item, i) => i === idx ? { ...item, ...patch } : item) })}
+ onRemove={() => commit({ pronunciations: pronunciations.filter((_, i) => i !== idx) })}
+ />
+ ))}
+ <div className="flex items-start gap-1.5">
+ <input
+ type="text" value={newPronunciation.term}
+ onChange={(e) => setNewPronunciation((current) => ({ ...current, term: e.target.value }))}
+ maxLength={L.VOICE_CANON_PRONUNCIATION_TERM_MAX} placeholder="new term"
+ disabled={disabled} aria-label="new pronunciation term" className={REL_SELECT_CLASS}
+ />
+ <input
+ type="text" value={newPronunciation.pronunciation}
+ onChange={(e) => setNewPronunciation((current) => ({ ...current, pronunciation: e.target.value }))}
+ maxLength={L.VOICE_CANON_PRONUNCIATION_VALUE_MAX} placeholder="how it is said"
+ disabled={disabled} aria-label="new pronunciation value" className={REL_SELECT_CLASS}
+ />
+ </div>
+ <button
+ type="button" disabled={disabled || !newTerm || !newValue || pronunciations.length >= L.VOICE_CANON_PRONUNCIATIONS_MAX}
+ onClick={addPronunciation}
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"
+ >
+ <Plus size={10} /> Add pronunciation
+ </button>
+ </div>
+ </BoxedSection>
+ );
+}
+
+function IdentityPackSection({ entry, onPatch, disabled }) {
+ const pack = entry.identityPack || {};
+ const assets = Array.isArray(pack.assets) ? pack.assets : [];
+ const approved = assets.filter((asset) => asset?.approved === true);
+ const counts = new Map();
+ for (const asset of approved) counts.set(asset.role, (counts.get(asset.role) || 0) + 1);
+ const missing = REQUIRED_IDENTITY_ROLES.filter((role) => !counts.get(role));
+ const ambiguous = REQUIRED_IDENTITY_ROLES.filter((role) => (counts.get(role) || 0) > 1);
+ const status = ambiguous.length ? 'ambiguous' : missing.length ? 'missing' : 'ready';
+ const commit = (patch) => onPatch?.({ identityPack: { ...pack, ...patch } });
+ const add = () => {
+ const imageRef = entry.imageRefs?.[0];
+ if (!imageRef) return;
+ commit({ assets: [...assets, { imageRef, role: 'neutral', approved: false }] });
+ };
+ return (
+ <BoxedSection icon={Images} label="Identity pack" summary={status}>
+ <p className="text-[10px] leading-snug text-gray-500">
+ Curate existing character references. Canon-locked production requires one approved neutral, profile, and full-body reference; duplicate approved roles are ambiguous.
+ </p>
+ {assets.length ? (
+ <div className="space-y-1.5">
+ {assets.map((asset, idx) => (
+ <div key={`${asset.role}-${asset.imageRef}-${idx}`} className="flex items-center gap-1.5">
+ <select
+ value={asset.imageRef} disabled={disabled} aria-label={`identity asset ${idx + 1} image`}
+ onChange={(e) => commit({ assets: assets.map((item, i) => i === idx ? { ...item, imageRef: e.target.value, approved: false } : item) })}
+ className={REL_SELECT_CLASS}
+ >
+ {(entry.imageRefs || []).map((ref) => <option key={ref} value={ref}>{ref}</option>)}
+ </select>
+ <select
+ value={asset.role} disabled={disabled} aria-label={`identity asset ${idx + 1} role`}
+ onChange={(e) => commit({ assets: assets.map((item, i) => i === idx ? { ...item, role: e.target.value, approved: false } : item) })}
+ className="w-32 shrink-0 px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50"
+ >
+ {IDENTITY_ASSET_ROLES.map((role) => <option key={role} value={role}>{role}</option>)}
+ </select>
+ <label className="inline-flex items-center gap-1 text-[10px] text-gray-300 whitespace-nowrap">
+ <input
+ type="checkbox" checked={asset.approved === true} disabled={disabled}
+ aria-label={`approve identity asset ${idx + 1} ${asset.role}`}
+ onChange={(e) => commit({ assets: assets.map((item, i) => i === idx ? { ...item, approved: e.target.checked } : item) })}
+ /> Approve
+ </label>
+ <button
+ type="button" disabled={disabled} onClick={() => commit({ assets: assets.filter((_, i) => i !== idx) })}
+ title="Remove identity asset" aria-label={`remove identity asset ${idx + 1}`}
+ className="shrink-0 text-gray-500 hover:text-port-error disabled:opacity-30"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ ))}
+ </div>
+ ) : <p className="text-[11px] text-gray-500 italic">No identity assets curated yet.</p>}
+ {entry.imageRefs?.length ? (
+ <button
+ type="button" onClick={add} disabled={disabled || assets.length >= L.IDENTITY_PACK_ASSETS_MAX}
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"
+ >
+ <Plus size={10} /> Add reference
+ </button>
+ ) : <p className="text-[11px] text-gray-500 italic">Generate or attach a character reference before curating this pack.</p>}
+ {status !== 'ready' ? <p className="text-[10px] text-port-warning">{ambiguous.length ? `Ambiguous: ${ambiguous.join(', ')}` : `Missing: ${missing.join(', ')}`}</p> : null}
+ </BoxedSection>
+ );
+}
+
export default function CharacterDetailEditor({ entry, onPatch, onExpand, expanding = false, disabled = false, characters = [] }) {
if (!entry) return null;
@@ -656,6 +880,10 @@ export default function CharacterDetailEditor({ entry, onPatch, onExpand, expand
idPrefix={entry.id}
/>
+ <VoiceCanonSection entry={entry} onPatch={onPatch} disabled={disabled} />
+
+ <IdentityPackSection entry={entry} onPatch={onPatch} disabled={disabled} />
+
<RelationshipsSection
entry={entry}
characters={characters}
diff --git a/client/src/components/universe/CharacterDetailEditor.test.jsx b/client/src/components/universe/CharacterDetailEditor.test.jsx
index 7ea80691d1..ed7baf409b 100644
--- a/client/src/components/universe/CharacterDetailEditor.test.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.test.jsx
@@ -163,3 +163,82 @@ describe('CharacterDetailEditor — character framework (#2175)', () => {
expect(screen.getByDisplayValue('I only matter if I win')).toBeInTheDocument();
});
});
+
+describe('CharacterDetailEditor — production package (#5378)', () => {
+ it('marks a voice-canon revision as approved', () => {
+ const onPatch = vi.fn();
+ render(<CharacterDetailEditor entry={ARIA} characters={[ARIA]} onPatch={onPatch} />);
+ fireEvent.click(screen.getByRole('button', { name: /Voice canon/i }));
+ fireEvent.click(screen.getByRole('checkbox', { name: /Candidate revision/i }));
+ expect(onPatch).toHaveBeenCalledWith({
+ voiceCanon: { version: 1, approved: true },
+ });
+ });
+
+ it('adds an identity reference as a candidate and surfaces missing required roles', () => {
+ const onPatch = vi.fn();
+ render(<CharacterDetailEditor entry={{ ...ARIA, imageRefs: ['neutral.png'] }} characters={[ARIA]} onPatch={onPatch} />);
+ fireEvent.click(screen.getByRole('button', { name: /Identity pack/i }));
+ expect(screen.getByText(/Missing: neutral, profile, full-body/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /Add reference/i }));
+ expect(onPatch).toHaveBeenCalledWith({
+ identityPack: { assets: [{ imageRef: 'neutral.png', role: 'neutral', approved: false }] },
+ });
+ });
+
+ it('revokes approval when an approved voice revision changes', () => {
+ const onPatch = vi.fn();
+ render(<CharacterDetailEditor entry={{
+ ...ARIA,
+ voiceCanon: { version: 2, description: 'measured', approved: true },
+ }} characters={[ARIA]} onPatch={onPatch} />);
+ fireEvent.click(screen.getByRole('button', { name: /Voice canon/i }));
+ const description = screen.getByRole('textbox', { name: /voice canon description/i });
+ fireEvent.change(description, { target: { value: 'more urgent' } });
+ fireEvent.blur(description);
+ expect(onPatch).toHaveBeenCalledWith({
+ voiceCanon: { version: 2, description: 'more urgent', approved: false },
+ });
+ });
+
+ it('returns a replacement identity asset to candidate state', () => {
+ const onPatch = vi.fn();
+ render(<CharacterDetailEditor entry={{
+ ...ARIA,
+ imageRefs: ['neutral.png', 'replacement.png'],
+ identityPack: { assets: [{ imageRef: 'neutral.png', role: 'neutral', approved: true }] },
+ }} characters={[ARIA]} onPatch={onPatch} />);
+ fireEvent.click(screen.getByRole('button', { name: /Identity pack/i }));
+ fireEvent.change(screen.getByRole('combobox', { name: /identity asset 1 image/i }), {
+ target: { value: 'replacement.png' },
+ });
+ expect(onPatch).toHaveBeenCalledWith({
+ identityPack: { assets: [{ imageRef: 'replacement.png', role: 'neutral', approved: false }] },
+ });
+ });
+
+ it('adds only a complete pronunciation row', () => {
+ const onPatch = vi.fn();
+ render(<CharacterDetailEditor entry={ARIA} characters={[ARIA]} onPatch={onPatch} />);
+ fireEvent.click(screen.getByRole('button', { name: /Voice canon/i }));
+
+ const addButton = screen.getByRole('button', { name: /Add pronunciation/i });
+ fireEvent.change(screen.getByRole('textbox', { name: /new pronunciation term/i }), {
+ target: { value: 'Aster' },
+ });
+ expect(addButton).toBeDisabled();
+ expect(onPatch).not.toHaveBeenCalled();
+
+ fireEvent.change(screen.getByRole('textbox', { name: /new pronunciation value/i }), {
+ target: { value: 'AS-ter' },
+ });
+ fireEvent.click(addButton);
+ expect(onPatch).toHaveBeenCalledWith({
+ voiceCanon: {
+ version: 1,
+ approved: false,
+ pronunciations: [{ term: 'Aster', pronunciation: 'AS-ter' }],
+ },
+ });
+ });
+});
diff --git a/client/src/lib/bibleLimits.js b/client/src/lib/bibleLimits.js
index 0dccd96347..f328bf3b96 100644
--- a/client/src/lib/bibleLimits.js
+++ b/client/src/lib/bibleLimits.js
@@ -87,6 +87,19 @@ export const BIBLE_LIMITS = Object.freeze({
TAGS_PER_ENTRY_MAX: 12,
SOURCE_SERIES_ID_MAX: 64,
VOICE_ID_MAX: 200,
+ VOICE_CANON_VERSION_MAX: 100000,
+ VOICE_CANON_DESCRIPTION_MAX: 1200,
+ VOICE_CANON_DELIVERY_MAX: 1200,
+ VOICE_CANON_RANGE_ITEM_MAX: 240,
+ VOICE_CANON_RANGE_MAX: 12,
+ VOICE_CANON_AVOID_ITEM_MAX: 240,
+ VOICE_CANON_AVOID_MAX: 12,
+ VOICE_CANON_PRONUNCIATION_TERM_MAX: 160,
+ VOICE_CANON_PRONUNCIATION_VALUE_MAX: 240,
+ VOICE_CANON_PRONUNCIATIONS_MAX: 24,
+ IDENTITY_PACK_ASSETS_MAX: 24,
+ IDENTITY_PACK_AVOID_ITEM_MAX: 240,
+ IDENTITY_PACK_AVOID_MAX: 12,
INGREDIENT_ID_MAX: 64,
// Reveal-gated canon / spoiler scoping (#2178).
SURFACE_DESCRIPTOR_MAX: 2000,
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index f3da14e7f6..a9e35d45c1 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -34,7 +34,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).
- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
-- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.
+- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.
- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. Adapter: `server/services/tribe.js`.
- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The brief/identity federates as `creativeCommission` so synced feedback can attach to the same commission; `schedule`, `runs`, `assignment`, `enabled`, and feedback view stay machine-local (the per-reaction `commissionFeedback` records federate separately). The opt-in Digital Twin music-taste configuration is bounded brief metadata; raw taste sources and per-run recipes never cross the wire. The file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).
diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.js
index 9eb447dfb9..91cb568010 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -13,7 +13,10 @@ import { z } from 'zod';
import { partialWithoutDefaults } from './zodCompat.js';
import { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.js';
import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';
-import { BIBLE_LIMITS, RELATIONSHIP_LINK_TYPES, RELATIONSHIP_OPPOSITION_AXES, ATTACHMENT_ROLES } from './storyBible.js';
+import {
+ BIBLE_LIMITS, RELATIONSHIP_LINK_TYPES, RELATIONSHIP_OPPOSITION_AXES,
+ ATTACHMENT_ROLES, VOICE_CANON_SOURCE_POLICIES, IDENTITY_ASSET_ROLES,
+} from './storyBible.js';
import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { CHECK_SCOPES, CHECK_SEVERITIES } from './editorial/checkRegistry.js';
@@ -424,6 +427,30 @@ const wrCharTextField = z.string().max(2000);
// `engine:voiceName` (e.g. `kokoro:af_heart`). Nullable so a UI clear path
// can null it explicitly.
const wrVoiceIdField = z.string().trim().max(200).nullable();
+// Portable production metadata. The nested schemas intentionally contain no
+// provider/profile/path fields: those are machine-local voice/media concerns,
+// not Universe canon and not wire-safe record data.
+const voiceCanonField = z.object({
+ version: z.number().int().min(1).max(BIBLE_LIMITS.VOICE_CANON_VERSION_MAX).optional(),
+ description: z.string().max(BIBLE_LIMITS.VOICE_CANON_DESCRIPTION_MAX).optional(),
+ defaultDelivery: z.string().max(BIBLE_LIMITS.VOICE_CANON_DELIVERY_MAX).optional(),
+ emotionalRange: z.array(z.string().trim().min(1).max(BIBLE_LIMITS.VOICE_CANON_RANGE_ITEM_MAX)).max(BIBLE_LIMITS.VOICE_CANON_RANGE_MAX).optional(),
+ avoid: z.array(z.string().trim().min(1).max(BIBLE_LIMITS.VOICE_CANON_AVOID_ITEM_MAX)).max(BIBLE_LIMITS.VOICE_CANON_AVOID_MAX).optional(),
+ pronunciations: z.array(z.object({
+ term: z.string().trim().min(1).max(BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_TERM_MAX),
+ pronunciation: z.string().trim().min(1).max(BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_VALUE_MAX),
+ }).strict()).max(BIBLE_LIMITS.VOICE_CANON_PRONUNCIATIONS_MAX).optional(),
+ sourcePolicy: z.enum(VOICE_CANON_SOURCE_POLICIES).nullable().optional(),
+ approved: z.boolean().optional(),
+}).strict();
+const identityPackField = z.object({
+ assets: z.array(z.object({
+ role: z.enum(IDENTITY_ASSET_ROLES),
+ imageRef: z.string().trim().min(1).max(BIBLE_LIMITS.IMAGE_REF_MAX),
+ approved: z.boolean().optional(),
+ }).strict()).max(BIBLE_LIMITS.IDENTITY_PACK_ASSETS_MAX).optional(),
+ avoid: z.array(z.string().trim().min(1).max(BIBLE_LIMITS.IDENTITY_PACK_AVOID_ITEM_MAX)).max(BIBLE_LIMITS.IDENTITY_PACK_AVOID_MAX).optional(),
+}).strict();
// Wardrobe array (A2). `id` is omitted on POSTs by the UI — the sanitizer
// fills it from the server-side UUID factory. Limits sourced from
// BIBLE_LIMITS so bumping the constant updates Zod automatically.
@@ -462,6 +489,8 @@ export const writersRoomCharacterCreateSchema = z.object({
background: wrCharTextField.optional(),
notes: wrCharTextField.optional(),
voiceId: wrVoiceIdField.optional(),
+ voiceCanon: voiceCanonField.optional(),
+ identityPack: identityPackField.optional(),
wardrobes: wrWardrobeField.optional(),
relationshipLinks: wrRelationshipLinksField.optional(),
}).strict();
@@ -474,6 +503,8 @@ export const writersRoomCharacterUpdateSchema = z.object({
background: wrCharTextField.optional(),
notes: wrCharTextField.optional(),
voiceId: wrVoiceIdField.optional(),
+ voiceCanon: voiceCanonField.optional(),
+ identityPack: identityPackField.optional(),
wardrobes: wrWardrobeField.optional(),
relationshipLinks: wrRelationshipLinksField.optional(),
}).strict();
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index c557ea4286..6bf855326f 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -67,7 +67,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// same rationale as v6/v7/v8: additive + gracefully degrading, but an older
// peer that re-sanitizes a universe through its moodBoardId-unaware
// `sanitizeTemplate` would silently strip the link and LWW the loss back.
- universes: 9,
+ // v10 = character `voiceCanon` and `identityPack` added (#5378). These are
+ // portable, federated production-canon fields; a ≤v9 peer would sanitize
+ // them away and LWW the loss back after an unrelated Universe edit.
+ universes: 10,
// v1 = post-split. Migrations 035/036 introduced the pipeline collection
// layout for issues and series.
// v2 = `stages.audio.audioMode` + `stages.audio.cues[]` added (whole-episode
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index e2b15d06af..fd17a56150 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -20,9 +20,10 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
// deliberate two-file edit.
// v6 = canon characters gained relationshipLinks[] (#1287); v7 = canon
// objects gained attachments[] (#1288); v8 adds styleReferences[]; v9 adds
- // moodBoardId (#4188). These are additive + version-gated so an older peer
+ // moodBoardId (#4188); v10 adds character production packages (#5378).
+ // These are additive + version-gated so an older peer
// cannot strip-then-LWW them.
- expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(9);
+ expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(10);
});
it('declares pipeline collection layout versions', () => {
@@ -50,14 +51,14 @@ describe('buildPortosMeta', () => {
it('returns { portosVersion, schemaVersions } with the live registry', async () => {
const meta = await buildPortosMeta();
expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);
- expect(meta.schemaVersions.universes).toBe(9);
+ expect(meta.schemaVersions.universes).toBe(10);
expect(meta.schemaVersions.pipelineIssues).toBe(3);
expect(meta.schemaVersions.pipelineSeries).toBe(12);
});
it('overrides merge into schemaVersions', async () => {
const meta = await buildPortosMeta({ schemaVersions: { future: 1 } });
- expect(meta.schemaVersions.universes).toBe(9);
+ expect(meta.schemaVersions.universes).toBe(10);
expect(meta.schemaVersions.future).toBe(1);
});
});
@@ -205,7 +206,12 @@ describe('scopeVersionDiff', () => {
// Sender is ahead on mediaCollections only; a universe transfer scopes to
// ['universes'] and stays compatible even though the union diff is not.
const union = compareSchemaVersions(
- { universes: 9, pipelineSeries: 2, pipelineIssues: 3, mediaCollections: 2 },
+ {
+ universes: PORTOS_SCHEMA_VERSIONS.universes,
+ pipelineSeries: 2,
+ pipelineIssues: 3,
+ mediaCollections: 2,
+ },
PORTOS_SCHEMA_VERSIONS,
);
expect(union.compatible).toBe(false); // mediaCollections 2 > 1
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index 8377c0457c..4647aec3b0 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -151,6 +151,24 @@ export const BIBLE_LIMITS = Object.freeze({
// `piper:en_GB-northern_english_male`). Caps generously since 3rd-party
// providers (ElevenLabs) use uuid-shaped voice ids.
VOICE_ID_MAX: 200,
+ // Versioned, portable voice-production intent (#5378). This records only
+ // creative direction and an approval decision; local profiles, providers,
+ // recordings, and training artifacts deliberately have no slot here.
+ VOICE_CANON_VERSION_MAX: 100000,
+ VOICE_CANON_DESCRIPTION_MAX: 1200,
+ VOICE_CANON_DELIVERY_MAX: 1200,
+ VOICE_CANON_RANGE_ITEM_MAX: 240,
+ VOICE_CANON_RANGE_MAX: 12,
+ VOICE_CANON_AVOID_ITEM_MAX: 240,
+ VOICE_CANON_AVOID_MAX: 12,
+ VOICE_CANON_PRONUNCIATION_TERM_MAX: 160,
+ VOICE_CANON_PRONUNCIATION_VALUE_MAX: 240,
+ VOICE_CANON_PRONUNCIATIONS_MAX: 24,
+ // Approved identity-pack assets are a curated view over imageRefs[], not a
+ // second image store. Only an existing managed reference can be assigned.
+ IDENTITY_PACK_ASSETS_MAX: 24,
+ IDENTITY_PACK_AVOID_ITEM_MAX: 240,
+ IDENTITY_PACK_AVOID_MAX: 12,
// Reveal-gated canon (#2178): `surfaceDescriptor` is the pre-reveal
// stand-in — what the world looks like BEFORE the spoiler is due ("the
// locked east wing" vs "the wing where the heir is imprisoned"). Roomy
@@ -162,6 +180,26 @@ export const BIBLE_LIMITS = Object.freeze({
REVEAL_ISSUE_MAX: 100000,
});
+// Portable production posture only. Performer identity, contracts, source
+// recordings, provider ids, and local artifact paths must never enter a
+// Universe record or its federated payload.
+export const VOICE_CANON_SOURCE_POLICIES = Object.freeze([
+ 'designed', 'consented-performance', 'licensed',
+]);
+const VOICE_CANON_SOURCE_POLICY_SET = new Set(VOICE_CANON_SOURCE_POLICIES);
+
+// Ordered both for the editor and for readiness output. `neutral`, `profile`,
+// and `full-body` are the minimum visual identity anchors; the other roles
+// enrich continuity without making a newly-curated character unusable.
+export const IDENTITY_ASSET_ROLES = Object.freeze([
+ 'neutral', 'profile', 'full-body', 'expression-gesture', 'wardrobe',
+ 'prop-scale', 'negative-identity',
+]);
+const IDENTITY_ASSET_ROLE_SET = new Set(IDENTITY_ASSET_ROLES);
+export const IDENTITY_PACK_REQUIRED_ROLES = Object.freeze([
+ 'neutral', 'profile', 'full-body',
+]);
+
// Canonical provenance vocabulary. `BIBLE_SOURCE.SERIES_EXTRACT` is the
// default for new bible-extracted entries; `UNIVERSE_EXPAND` is stamped on
// canon backfilled from a v1 universe's categories; `MANUAL` is user-authored.
@@ -496,6 +534,100 @@ function deriveReferenceSheetImageRef(raw) {
return trimmed;
}
+function sanitizeVoiceCanon(raw) {
+ if (!isPlainObject(raw)) return null;
+ const version = Number.isInteger(raw.version) && raw.version > 0
+ ? Math.min(raw.version, BIBLE_LIMITS.VOICE_CANON_VERSION_MAX)
+ : 1;
+ const pronunciations = sanitizeListWith(raw.pronunciations, (item) => {
+ if (!isPlainObject(item)) return null;
+ const term = trimTo(item.term, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_TERM_MAX);
+ const pronunciation = trimTo(item.pronunciation, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_VALUE_MAX);
+ return term && pronunciation ? { term, pronunciation } : null;
+ }, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATIONS_MAX);
+ const sourcePolicy = trimTo(raw.sourcePolicy, 64);
+ return {
+ version,
+ description: trimTo(raw.description, BIBLE_LIMITS.VOICE_CANON_DESCRIPTION_MAX),
+ defaultDelivery: trimTo(raw.defaultDelivery, BIBLE_LIMITS.VOICE_CANON_DELIVERY_MAX),
+ emotionalRange: cleanStringArray(raw.emotionalRange, BIBLE_LIMITS.VOICE_CANON_RANGE_ITEM_MAX, BIBLE_LIMITS.VOICE_CANON_RANGE_MAX),
+ avoid: cleanStringArray(raw.avoid, BIBLE_LIMITS.VOICE_CANON_AVOID_ITEM_MAX, BIBLE_LIMITS.VOICE_CANON_AVOID_MAX),
+ pronunciations,
+ sourcePolicy: VOICE_CANON_SOURCE_POLICY_SET.has(sourcePolicy) ? sourcePolicy : null,
+ approved: raw.approved === true,
+ };
+}
+
+function sanitizeIdentityPack(raw, imageRefs) {
+ if (!isPlainObject(raw)) return null;
+ const seen = new Set();
+ const assets = [];
+ for (const item of Array.isArray(raw.assets) ? raw.assets : []) {
+ if (!isPlainObject(item)) continue;
+ const role = trimTo(item.role, 64);
+ const imageRef = trimTo(item.imageRef, BIBLE_LIMITS.IMAGE_REF_MAX);
+ // The pack may only curate an image the character already owns. This
+ // prevents arbitrary filesystem/provider pointers from becoming canon.
+ if (!IDENTITY_ASSET_ROLE_SET.has(role) || !imageRefs.includes(imageRef)) continue;
+ const key = `${role}:${imageRef}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ assets.push({ role, imageRef, approved: item.approved === true });
+ if (assets.length >= BIBLE_LIMITS.IDENTITY_PACK_ASSETS_MAX) break;
+ }
+ const avoid = cleanStringArray(raw.avoid, BIBLE_LIMITS.IDENTITY_PACK_AVOID_ITEM_MAX, BIBLE_LIMITS.IDENTITY_PACK_AVOID_MAX);
+ return assets.length || avoid.length ? { assets, avoid } : null;
+}
+
+/**
+ * Resolve a portable identity-pack status for canon-locked production.
+ * Consumers must refuse (or visibly degrade) a locked render unless status is
+ * `ready`; an empty candidate pack is deliberately `missing`, never ready.
+ */
+export function characterIdentityPackReadiness(character) {
+ const approved = Array.isArray(character?.identityPack?.assets)
+ ? character.identityPack.assets.filter((asset) => asset?.approved === true)
+ : [];
+ const byRole = new Map();
+ for (const asset of approved) {
+ if (!IDENTITY_ASSET_ROLE_SET.has(asset?.role)) continue;
+ const rows = byRole.get(asset.role) || [];
+ rows.push(asset);
+ byRole.set(asset.role, rows);
+ }
+ const missing = IDENTITY_PACK_REQUIRED_ROLES.filter((role) => !(byRole.get(role)?.length));
+ const ambiguous = IDENTITY_PACK_REQUIRED_ROLES.filter((role) => (byRole.get(role)?.length || 0) > 1);
+ return {
+ status: ambiguous.length ? 'ambiguous' : missing.length ? 'missing' : 'ready',
+ missing,
+ ambiguous,
+ assets: approved,
+ };
+}
+
+/**
+ * Preserve v10 character production fields when an older peer wins LWW with
+ * a character shape that could not represent them. A v10-aware sender's
+ * omission is an intentional clear and must pass through unchanged.
+ */
+export function preserveLegacyCharacterProductionPackages(remoteCharacters, localCharacters, senderUniversesVersion) {
+ if ((Number(senderUniversesVersion) || 0) >= 10
+ || !Array.isArray(remoteCharacters)
+ || !Array.isArray(localCharacters)) return remoteCharacters;
+ const localById = new Map(
+ localCharacters.filter((character) => character?.id).map((character) => [character.id, character]),
+ );
+ return remoteCharacters.map((character) => {
+ const localCharacter = localById.get(character?.id);
+ if (!localCharacter) return character;
+ return {
+ ...character,
+ ...(!character.voiceCanon && localCharacter.voiceCanon ? { voiceCanon: localCharacter.voiceCanon } : {}),
+ ...(!character.identityPack && localCharacter.identityPack ? { identityPack: localCharacter.identityPack } : {}),
+ };
+ });
+}
+
// The legacy 'standard' variant lives in `character.referenceSheetImageRef`;
// every other variant lives in `character.referenceSheets[<id>]`. Exported so
// every reader/writer of either slot uses the same constant — the alternative
@@ -949,6 +1081,8 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,
);
const created = preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso();
const imageRefs = cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX);
+ const voiceCanon = sanitizeVoiceCanon(raw.voiceCanon);
+ const identityPack = sanitizeIdentityPack(raw.identityPack, imageRefs);
return {
id: ensureId(raw.id, idPrefix),
name,
@@ -1027,10 +1161,16 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,
// Voice binding for VO synthesis (kokoro/piper local OSS, ElevenLabs
// when configured). null = use the project default at synth time.
voiceId: trimTo(raw.voiceId, BIBLE_LIMITS.VOICE_ID_MAX) || null,
+ // Optional portable production direction. Its allowlisted sanitizer keeps
+ // local profile ids, recordings, provider ids, and model revisions out.
+ ...(voiceCanon ? { voiceCanon } : {}),
imageRefs,
// Pinned visual anchor (A3). One of imageRefs marked canonical so
// downstream renders + the UI know which to lean on.
primaryImageRef: derivePrimaryImageRef(raw.primaryImageRef, imageRefs),
+ // Curated role assignments over existing imageRefs[]. Candidates remain
+ // unapproved until the editor explicitly approves them.
+ ...(identityPack ? { identityPack } : {}),
// Generated character reference sheet filename (lives in data/image-refs/,
// not in imageRefs[] — the sheet is operational metadata, not a candidate
// for arbitrary panel reference). Basename-validated so an LLM-extracted
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index f285e0cfc1..9029c76b1c 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -40,6 +40,8 @@ const {
isCanonEntryGatedForIssue,
canonHasRevealGated,
revealGatedCanonRows,
+ characterIdentityPackReadiness,
+ preserveLegacyCharacterProductionPackages,
} = storyBible;
const WORK_ID = 'wr-work-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
@@ -301,6 +303,93 @@ describe('storyBible — sanitizeCharacter', () => {
});
});
+ describe('portable production package (#5378)', () => {
+ it('keeps voice canon bounded and strips local artifact pointers', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ voiceCanon: {
+ version: 2,
+ description: 'warm low alto',
+ defaultDelivery: 'measured',
+ emotionalRange: ['guarded', 'wry'],
+ avoid: ['announcer projection'],
+ pronunciations: [{ term: 'Aster Vale', pronunciation: 'AS-ter vayl', profileId: 'local-only' }],
+ sourcePolicy: 'designed',
+ approved: true,
+ providerId: 'not-portable',
+ artifactPath: '/machine-local/voice.wav',
+ },
+ });
+ expect(out.voiceCanon).toEqual({
+ version: 2,
+ description: 'warm low alto',
+ defaultDelivery: 'measured',
+ emotionalRange: ['guarded', 'wry'],
+ avoid: ['announcer projection'],
+ pronunciations: [{ term: 'Aster Vale', pronunciation: 'AS-ter vayl' }],
+ sourcePolicy: 'designed',
+ approved: true,
+ });
+ expect(out.voiceCanon).not.toHaveProperty('providerId');
+ expect(out.voiceCanon).not.toHaveProperty('artifactPath');
+ });
+
+ it('keeps identity assets as unapproved candidates until explicit approval', () => {
+ const out = sanitizeCharacter({
+ name: 'A', imageRefs: ['neutral.png', 'profile.png', 'body.png'],
+ identityPack: {
+ assets: [
+ { role: 'neutral', imageRef: 'neutral.png' },
+ { role: 'profile', imageRef: 'profile.png', approved: true },
+ { role: 'full-body', imageRef: 'body.png', approved: true },
+ { role: 'neutral', imageRef: '/local/escape.png', approved: true },
+ ],
+ avoid: ['different eye color'],
+ },
+ });
+ expect(out.identityPack).toEqual({
+ assets: [
+ { role: 'neutral', imageRef: 'neutral.png', approved: false },
+ { role: 'profile', imageRef: 'profile.png', approved: true },
+ { role: 'full-body', imageRef: 'body.png', approved: true },
+ ],
+ avoid: ['different eye color'],
+ });
+ expect(characterIdentityPackReadiness(out)).toMatchObject({
+ status: 'missing', missing: ['neutral'], ambiguous: [],
+ });
+ });
+
+ it('reports ready, missing, and ambiguous required identity roles', () => {
+ const ready = { identityPack: { assets: [
+ { role: 'neutral', imageRef: 'n.png', approved: true },
+ { role: 'profile', imageRef: 'p.png', approved: true },
+ { role: 'full-body', imageRef: 'b.png', approved: true },
+ ] } };
+ expect(characterIdentityPackReadiness(ready)).toMatchObject({ status: 'ready', missing: [], ambiguous: [] });
+ const ambiguous = { identityPack: { assets: [
+ ...ready.identityPack.assets,
+ { role: 'profile', imageRef: 'p2.png', approved: true },
+ ] } };
+ expect(characterIdentityPackReadiness(ambiguous)).toMatchObject({ status: 'ambiguous', ambiguous: ['profile'] });
+ });
+
+ it('preserves packages from a pre-v10 peer but honors a v10 clear', () => {
+ const local = [{
+ id: 'chr-1', name: 'A',
+ voiceCanon: { version: 2, approved: true },
+ identityPack: { assets: [{ role: 'neutral', imageRef: 'n.png', approved: true }] },
+ }];
+ const remote = [{ id: 'chr-1', name: 'A from peer' }];
+ expect(preserveLegacyCharacterProductionPackages(remote, local, 9)[0]).toMatchObject({
+ name: 'A from peer',
+ voiceCanon: local[0].voiceCanon,
+ identityPack: local[0].identityPack,
+ });
+ expect(preserveLegacyCharacterProductionPackages(remote, local, 10)).toEqual(remote);
+ });
+ });
+
describe('wardrobes (Cluster A)', () => {
it('defaults to an empty array when omitted', () => {
const out = sanitizeCharacter({ name: 'A' });
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index d34406728a..aa00ae7108 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -1,4 +1,30 @@
+import {
+ BIBLE_LIMITS,
+ IDENTITY_ASSET_ROLES,
+ VOICE_CANON_SOURCE_POLICIES,
+} from './storyBible.js';
+
const isNonEmptyStr = (v) => typeof v === 'string' && v.trim().length > 0;
+const IDENTITY_ASSET_ROLE_SET = new Set(IDENTITY_ASSET_ROLES);
+const VOICE_CANON_SOURCE_POLICY_SET = new Set(VOICE_CANON_SOURCE_POLICIES);
+
+const boundedWireString = (value, max) => (
+ typeof value === 'string' ? value.trim().slice(0, max) : ''
+);
+
+const portableStringArray = (value, itemMax, listMax) => {
+ if (!Array.isArray(value)) return [];
+ const seen = new Set();
+ const result = [];
+ for (const item of value) {
+ const text = boundedWireString(item, itemMax);
+ if (!text || seen.has(text)) continue;
+ seen.add(text);
+ result.push(text);
+ if (result.length >= listMax) break;
+ }
+ return result;
+};
/**
* Normalize the `deleted` + `deletedAt` tombstone fields on a raw record.
@@ -35,6 +61,89 @@ export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = tru
return shared;
}
+// Defense in depth for Universe character production packages (#5378). The
+// record sanitizer already allowlists these nested fields on normal reads and
+// writes, but peer sync is a privacy boundary: old/corrupt persisted records
+// must not send local profile ids, provider ids, artifact paths, recordings, or
+// performer/source material merely because they bypassed a normal PATCH.
+function stripUniverseCharacterLocalProductionFields(record) {
+ if (!Array.isArray(record.characters)) return record;
+ return {
+ ...record,
+ characters: record.characters.map((character) => {
+ if (!character || typeof character !== 'object' || Array.isArray(character)) return character;
+ const { voiceCanon, identityPack, ...characterRest } = character;
+ const portableVoiceCanon = voiceCanon && typeof voiceCanon === 'object' && !Array.isArray(voiceCanon) ? {
+ version: Number.isInteger(voiceCanon.version) && voiceCanon.version > 0
+ ? Math.min(voiceCanon.version, BIBLE_LIMITS.VOICE_CANON_VERSION_MAX)
+ : 1,
+ description: boundedWireString(voiceCanon.description, BIBLE_LIMITS.VOICE_CANON_DESCRIPTION_MAX),
+ defaultDelivery: boundedWireString(voiceCanon.defaultDelivery, BIBLE_LIMITS.VOICE_CANON_DELIVERY_MAX),
+ emotionalRange: portableStringArray(
+ voiceCanon.emotionalRange,
+ BIBLE_LIMITS.VOICE_CANON_RANGE_ITEM_MAX,
+ BIBLE_LIMITS.VOICE_CANON_RANGE_MAX,
+ ),
+ avoid: portableStringArray(
+ voiceCanon.avoid,
+ BIBLE_LIMITS.VOICE_CANON_AVOID_ITEM_MAX,
+ BIBLE_LIMITS.VOICE_CANON_AVOID_MAX,
+ ),
+ pronunciations: (Array.isArray(voiceCanon.pronunciations) ? voiceCanon.pronunciations : [])
+ .flatMap((item) => {
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return [];
+ const term = boundedWireString(item.term, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_TERM_MAX);
+ const pronunciation = boundedWireString(
+ item.pronunciation,
+ BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_VALUE_MAX,
+ );
+ return term && pronunciation ? [{ term, pronunciation }] : [];
+ })
+ .slice(0, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATIONS_MAX),
+ sourcePolicy: VOICE_CANON_SOURCE_POLICY_SET.has(voiceCanon.sourcePolicy)
+ ? voiceCanon.sourcePolicy
+ : null,
+ approved: voiceCanon.approved === true,
+ } : null;
+ const imageRefs = Array.isArray(characterRest.imageRefs) ? characterRest.imageRefs : [];
+ const seenAssets = new Set();
+ const portableAssets = (Array.isArray(identityPack?.assets) ? identityPack.assets : [])
+ .flatMap((asset) => {
+ if (!asset || typeof asset !== 'object' || Array.isArray(asset)
+ || !IDENTITY_ASSET_ROLE_SET.has(asset.role)
+ || typeof asset.imageRef !== 'string'
+ || !imageRefs.includes(asset.imageRef)) return [];
+ const assetKey = `${asset.role}:${asset.imageRef}`;
+ if (seenAssets.has(assetKey)) return [];
+ seenAssets.add(assetKey);
+ return [{
+ role: asset.role,
+ imageRef: asset.imageRef,
+ approved: asset.approved === true,
+ }];
+ })
+ .slice(0, BIBLE_LIMITS.IDENTITY_PACK_ASSETS_MAX);
+ const portableIdentityPack = identityPack && typeof identityPack === 'object' && !Array.isArray(identityPack)
+ ? {
+ ...(Array.isArray(identityPack.assets) ? { assets: portableAssets } : {}),
+ ...(Array.isArray(identityPack.avoid) ? {
+ avoid: portableStringArray(
+ identityPack.avoid,
+ BIBLE_LIMITS.IDENTITY_PACK_AVOID_ITEM_MAX,
+ BIBLE_LIMITS.IDENTITY_PACK_AVOID_MAX,
+ ),
+ } : {}),
+ }
+ : null;
+ return {
+ ...characterRest,
+ ...(portableVoiceCanon ? { voiceCanon: portableVoiceCanon } : {}),
+ ...(portableIdentityPack ? { identityPack: portableIdentityPack } : {}),
+ };
+ }),
+ };
+}
+
// Single source of truth for what fields cross the federated-peer wire.
//
// Two transports carry universe / series / issue records between peers:
@@ -171,7 +280,8 @@ export function sanitizeRecordForWire(kind, record) {
if (kind === 'universe' || kind === 'series') {
const { imageMode: _imageMode, imageModelId: _imageModelId, ...noPinRest } = rest;
if (kind === 'universe') {
- const { styleImageRefs: _styleImageRefs, ...universeRest } = noPinRest;
+ const portableUniverse = stripUniverseCharacterLocalProductionFields(noPinRest);
+ const { styleImageRefs: _styleImageRefs, ...universeRest } = portableUniverse;
return { ...universeRest, ...sanitizeSoftDeleteFields(record) };
}
return { ...noPinRest, ...sanitizeSoftDeleteFields(record) };
diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.js
index 1c5ad63cbb..2b68dfece7 100644
--- a/server/lib/syncWire.test.js
+++ b/server/lib/syncWire.test.js
@@ -214,6 +214,39 @@ describe('syncWire', () => {
expect(JSON.stringify(withPin)).toBe(JSON.stringify(without));
});
+ it('keeps only portable character production canon on the universe wire (#5378)', () => {
+ const wire = sanitizeRecordForWire('universe', {
+ id: 'u1', name: 'U',
+ characters: [{
+ id: 'chr-1', name: 'A', imageRefs: ['neutral.png'],
+ voiceCanon: {
+ version: 2, description: 'warm low alto', sourcePolicy: 'designed', approved: true,
+ emotionalRange: ['guarded', { recordingPath: '/private/range.wav' }],
+ avoid: ['announcer', { providerId: 'private-provider' }],
+ pronunciations: [{
+ term: 'Aster', pronunciation: 'AS-ter', recordingPath: '/private/pronunciation.wav',
+ }],
+ profileId: 'machine-local-profile', artifactPath: '/private/voice.wav', performerName: 'private',
+ },
+ identityPack: {
+ assets: [{ role: 'neutral', imageRef: 'neutral.png', approved: true, localPath: '/private/image.png' }],
+ avoid: ['different eye color', { trainingDataset: 'private' }], trainingDataset: 'private',
+ },
+ }],
+ });
+ expect(wire.characters[0].voiceCanon).toEqual({
+ version: 2, description: 'warm low alto', defaultDelivery: '',
+ emotionalRange: ['guarded'], avoid: ['announcer'],
+ pronunciations: [{ term: 'Aster', pronunciation: 'AS-ter' }],
+ sourcePolicy: 'designed', approved: true,
+ });
+ expect(wire.characters[0].identityPack).toEqual({
+ assets: [{ role: 'neutral', imageRef: 'neutral.png', approved: true }],
+ avoid: ['different eye color'],
+ });
+ expect(JSON.stringify(wire)).not.toMatch(/machine-local|private/);
+ });
+
it('does NOT strip styleImageRefs from series/issue wire form (universe-only field)', () => {
// The strip is scoped to `kind === 'universe'` — series/issue records
// never carry styleImageRefs, but a stray value (hand-edit, corrupted
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 8e5043f03d..7f5340831e 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -1890,6 +1890,34 @@ describe('validation.js', () => {
});
});
+ describe('writersRoomCharacterUpdateSchema — production package (#5378)', () => {
+ it('accepts portable voice canon and approved identity assets', () => {
+ const result = writersRoomCharacterUpdateSchema.safeParse({
+ voiceCanon: {
+ version: 2,
+ description: 'warm low alto',
+ pronunciations: [{ term: 'Aster Vale', pronunciation: 'AS-ter vayl' }],
+ sourcePolicy: 'designed',
+ approved: true,
+ },
+ identityPack: {
+ assets: [{ role: 'neutral', imageRef: 'neutral.png', approved: true }],
+ avoid: ['different eye color'],
+ },
+ });
+ expect(result.success).toBe(true);
+ });
+
+ it('rejects local-artifact keys and invalid asset roles', () => {
+ expect(writersRoomCharacterUpdateSchema.safeParse({
+ voiceCanon: { description: 'warm', providerId: 'local-profile' },
+ }).success).toBe(false);
+ expect(writersRoomCharacterUpdateSchema.safeParse({
+ identityPack: { assets: [{ role: 'arbitrary', imageRef: 'ref.png' }] },
+ }).success).toBe(false);
+ });
+ });
+
describe('writersRoomObjectUpdateSchema — attachments (#1288)', () => {
it('accepts a well-formed attachment', () => {
const result = writersRoomObjectUpdateSchema.safeParse({
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 85a4fffc5c..6b35b724fe 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -163,19 +163,19 @@ describe('dataSync — universe category', () => {
const snap = await dataSync.getSnapshot('universe');
expect(snap.portosMeta).toBeDefined();
expect(typeof snap.portosMeta.portosVersion).toBe('string');
- expect(snap.portosMeta.schemaVersions.universes).toBe(9);
+ expect(snap.portosMeta.schemaVersions.universes).toBe(10);
});
it('applyRemote rejects when sender schemaVersions are AHEAD of local code', async () => {
writeUniverseState({ universes: [], runs: [] });
const result = await dataSync.applyRemote('universe', {
universes: [{ id: 'u-new', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }],
- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 10 } } });
+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 11 } } });
expect(result.applied).toBe(false);
expect(result.count).toBe(0);
expect(result.blockedBySchema).toBeDefined();
expect(result.blockedBySchema.ahead).toEqual([
- { category: 'universes', senderV: 10, receiverV: 9 },
+ { category: 'universes', senderV: 11, receiverV: 10 },
]);
expect(result.blockedBySchema.senderPortosVersion).toBe('99.0.0');
// Nothing was written.
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 1fec30a74d..d3c1d980c5 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -41,7 +41,7 @@ import { findOrCreateUniverseCollection, findOrCreateSeriesCollection, addItem a
import { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';
import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';
import { mergePeerAnnotations } from '../mediaAnnotations.js';
-import { isStr } from '../../lib/storyBible.js';
+import { isStr, preserveLegacyCharacterProductionPackages } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { maybeJournalBeforeOverwrite, flushBaseHashes, setSyncBaseHash, contentHashForRecord } from '../../lib/conflictJournal.js';
@@ -495,6 +495,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
let applied = 0;
const overridden = [];
const senderCannotRepresentClimax = (Number(manifest?.portosSchemaVersions?.pipelineIssues) || 0) < 3;
+ const senderUniversesVersion = Number(manifest?.portosSchemaVersions?.universes) || 0;
// Records whose insert threw an UNEXPECTED (non-duplicate) error — they did
// NOT land. Surfaced as a pending condition (like legacyCanonPendingFailures)
// so processManifest leaves the cursor un-advanced and the watcher retries,
@@ -562,6 +563,16 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
&& existing.arcRole === 'climax' && record.arcRole !== 'climax') {
record = { ...record, arcRole: 'climax' };
}
+ if (kind === 'universe') {
+ record = {
+ ...record,
+ characters: preserveLegacyCharacterProductionPackages(
+ record.characters,
+ existing.characters,
+ senderUniversesVersion,
+ ),
+ };
+ }
// Non-blocking conflict journal for every synced record kind — a
// share-bucket import that LWW-overwrites a locally-diverged record
// archives the losing local version first. Issues are included now
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 981798c978..e857422c8a 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2312,7 +2312,43 @@ describe('sharing round-trip', () => {
const exp = await exporter.exportSeries(s.id, bucket.id);
const manifest = JSON.parse(readFileSync(join(tempBucket, 'manifests', exp.filename), 'utf-8'));
expect(manifest.portosSchemaVersions).toBeDefined();
- expect(manifest.portosSchemaVersions.universes).toBe(9);
+ expect(manifest.portosSchemaVersions.universes).toBe(10);
+ });
+
+ it('preserves character production packages when an older peer wins universe LWW', async () => {
+ const bucket = await buckets.createBucket({ name: 'LegacyUniverseBucket', path: tempBucket, mode: 'auto-merge' });
+ const u = await universeSvc.createUniverse({
+ name: 'Legacy Compatible Universe',
+ characters: [{
+ id: 'char-voice',
+ name: 'Aster',
+ imageRefs: ['fakeasset.png'],
+ voiceCanon: { version: 1, description: 'measured alto', approved: true },
+ identityPack: { assets: [{ role: 'neutral', imageRef: 'fakeasset.png', approved: true }] },
+ }],
+ });
+ const exp = await exporter.exportUniverse(u.id, bucket.id);
+ const recordPath = join(tempBucket, 'records', 'universes', `${u.id}.json`);
+ const remote = JSON.parse(readFileSync(recordPath, 'utf-8'));
+ remote.name = 'Older Peer Rename';
+ remote.updatedAt = new Date(Date.now() + 60_000).toISOString();
+ remote.characters = remote.characters.map(({ voiceCanon, identityPack, ...character }) => character);
+ writeFileSync(recordPath, JSON.stringify(remote, null, 2));
+
+ const manifestPath = join(tempBucket, 'manifests', exp.filename);
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
+ manifest.portosSchemaVersions.universes = 9;
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
+ simulateRemoteSender(tempBucket, exp.filename);
+
+ const result = await importer.processManifest(bucket.id, exp.filename);
+ expect(result.processed).toBe(true);
+ const merged = await universeSvc.getUniverse(u.id);
+ expect(merged.name).toBe('Older Peer Rename');
+ expect(merged.characters[0].voiceCanon).toMatchObject({ description: 'measured alto', approved: true });
+ expect(merged.characters[0].identityPack.assets).toEqual([
+ { role: 'neutral', imageRef: 'fakeasset.png', approved: true },
+ ]);
});
it('importer rejects a manifest when the sender is AHEAD on a category the manifest CARRIES', async () => {
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 9e046234fe..aae3f72f7e 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3670,17 +3670,17 @@ describe('peerSync', () => {
describe('receiver — applyIncomingPush', () => {
it('rejects when sender schemaVersions.universes is AHEAD of local code', async () => {
- // Local code is at universes:9 (see server/lib/schemaVersions.js).
- // A push from a sender on universes:10 must NOT touch local state.
+ // Local code is at universes:10 (see server/lib/schemaVersions.js).
+ // A push from a sender on universes:11 must NOT touch local state.
const rejection = await applyIncomingPush({
kind: 'universe',
record: { id: 'u1', name: 'Foo' },
assetManifest: [],
sourceInstanceId: 'peer-a',
- portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 10 } },
+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 11 } },
}).catch((err) => err);
expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');
- expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 10, receiverV: 9 }]);
+ expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 11, receiverV: 10 }]);
expect(rejection.details.senderPortosVersion).toBe('99.0.0');
// Receiver MUST stamp its OWN PortOS version so the sender can show
// the user "peer X is on PortOS vY" — without this, the sender would
@@ -3965,7 +3965,7 @@ describe('peerSync', () => {
expect(call).toBeDefined();
const body = JSON.parse(call[1].body);
expect(body.portosMeta).toBeDefined();
- expect(body.portosMeta.schemaVersions.universes).toBe(9);
+ expect(body.portosMeta.schemaVersions.universes).toBe(10);
expect(typeof body.portosMeta.portosVersion).toBe('string');
});
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 8b7d343e5e..4e8c7e8476 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -1299,6 +1299,26 @@ describe("universeBuilder service", () => {
const after = await svc.getUniverse(w.id);
expect(after.moodBoardId).toBe("mb-remote");
});
+
+ it('preserves production canon when a pre-v10 sender wins an unrelated edit (#5378)', async () => {
+ const w = await seedWorld();
+ await svc.updateUniverse(w.id, {
+ characters: [{
+ id: 'chr-1', name: 'A', imageRefs: ['neutral.png', 'profile.png', 'body.png'],
+ voiceCanon: { version: 1, description: 'warm low alto', approved: true },
+ identityPack: { assets: [{ role: 'neutral', imageRef: 'neutral.png', approved: true }] },
+ }],
+ });
+ const local = await svc.getUniverse(w.id);
+ const r = await svc.mergeUniversesFromSync(
+ [{ ...local, name: 'Old peer rename', characters: [{ id: 'chr-1', name: 'A', imageRefs: ['neutral.png', 'profile.png', 'body.png'] }], updatedAt: new Date(Date.now() + 60_000).toISOString() }],
+ { senderSchemaVersions: { universes: 9 } },
+ );
+ expect(r.applied).toBe(true);
+ const after = await svc.getUniverse(w.id);
+ expect(after.characters[0].voiceCanon).toMatchObject({ description: 'warm low alto', approved: true });
+ expect(after.characters[0].identityPack.assets).toEqual([{ role: 'neutral', imageRef: 'neutral.png', approved: true }]);
+ });
});
describe("pruneTombstonedUniverses", () => {
diff --git a/server/services/universeBuilder/sync.js b/server/services/universeBuilder/sync.js
index f60b949476..ef3440ddf4 100644
--- a/server/services/universeBuilder/sync.js
+++ b/server/services/universeBuilder/sync.js
@@ -8,7 +8,7 @@
* re-exports this module so existing import paths keep working.
*/
-import { isStr } from '../../lib/storyBible.js';
+import { isStr, preserveLegacyCharacterProductionPackages } from '../../lib/storyBible.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
deleteSyncBaseHash,
@@ -57,6 +57,7 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
// The version gate only rejects AHEAD senders — a behind/no-meta sender's
// record flows through this merge, and its sanitized form omits the field.
const senderKnowsMoodBoardId = (Number(senderSchemaVersions?.universes) || 0) >= 9;
+ const senderUniversesVersion = Number(senderSchemaVersions?.universes) || 0;
if (!Array.isArray(remoteUniverses)) return { applied: false, count: 0 };
// Records that transitioned to deleted via this merge get their orphan
// cascade fired after the write queue releases — matches the side-effect
@@ -149,6 +150,11 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
if (!sanitized.moodBoardId && local.moodBoardId && !senderKnowsMoodBoardId) {
sanitized.moodBoardId = local.moodBoardId;
}
+ sanitized.characters = preserveLegacyCharacterProductionPackages(
+ sanitized.characters,
+ local.characters,
+ senderUniversesVersion,
+ );
// Non-blocking conflict journal: archive the about-to-be-lost local
// version when BOTH sides diverged from the last synced base. Always
// advances the base hash (clean or conflict) so the next snapshot
diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.js
index c15a9285f0..3020af2e57 100644
--- a/server/services/writersRoom/characters.js
+++ b/server/services/writersRoom/characters.js
@@ -21,7 +21,10 @@ export const {
idPrefix: 'wr-char-',
dedupKey: (entry) => normalizeBibleName(entry?.name),
primaryFields: ['name'],
- editableFields: ['aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes'],
+ editableFields: [
+ 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes',
+ 'voiceCanon', 'identityPack',
+ ],
requireOnCreate: (patch) => (String(patch?.name || '').trim() ? null : 'Character name required'),
conflictMessage: ({ name }) => `A character named "${name}" already exists`,
notFoundLabel: 'Character',
diff --git a/server/services/writersRoom/characters.test.js b/server/services/writersRoom/characters.test.js
index f373883c7c..a5140bc057 100644
--- a/server/services/writersRoom/characters.test.js
+++ b/server/services/writersRoom/characters.test.js
@@ -70,6 +70,23 @@ describe('writers room — characters CRUD', () => {
expect(updated.source).toBe('user');
});
+ it('persists portable character production metadata accepted by the route schema', async () => {
+ const id = await newWork();
+ const c = await createCharacter(id, {
+ name: 'Mila',
+ voiceCanon: { version: 1, description: 'warm alto', approved: true },
+ identityPack: { avoid: ['different eye color'] },
+ });
+ expect(c.voiceCanon).toMatchObject({ version: 1, description: 'warm alto', approved: true });
+ expect(c.identityPack).toEqual({ assets: [], avoid: ['different eye color'] });
+
+ const updated = await updateCharacter(id, c.id, {
+ voiceCanon: { version: 2, description: 'urgent alto', approved: false },
+ });
+ expect(updated.voiceCanon).toMatchObject({ version: 2, description: 'urgent alto', approved: false });
+ expect(updated.identityPack).toEqual(c.identityPack);
+ });
+
it('deletes a profile', async () => {
const id = await newWork();
const c = await createCharacter(id, { name: 'Vox' });