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: structured character relationships + opposing-force tagging (#1287)

[._.]/ Adam Eivy9b8d37273626
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a39fe30362..616b043b69 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Structured character relationships + opposing-force tagging.** A character's relationships used to be a single free-text field — readable, but invisible to tooling. Each universe character now also carries **structured relationship links**: pick a target character from the cast, tag the dynamic (ally / antagonist / rival / mentor / love-interest / family / custom), and add a short description. A link can optionally carry an **opposing force** — a binary tension the reader watches to see reverse (hunter/prey, winner/loser, predator/prey, smart/dumb, or a custom axis), with each side's role and a note ("reader is waiting to see if these flip"). The Cast editor surfaces opposition pairs prominently (they're a story spine, not every story has them). Three new editorial checks validate the web: **Relationship reciprocity** (A links B but B doesn't link back), **Relationship dangling target** (a link points at a deleted character), and an advisory **Opposition role-reversal payoff** (surfaces every tagged opposing-force pair so you can confirm the roles ever reverse — or deliberately don't). The legacy prose `relationships` field is untouched; `relationshipLinks` is purely additive and version-gated for cross-machine sync so an older peer can't silently strip it. (`server/lib/storyBible.js`, `server/lib/validation.js`, `server/lib/editorial/checkRegistry.js`, `server/lib/schemaVersions.js`, `client/src/components/universe/CharacterDetailEditor.jsx`) (#1287)
+
- **Reverse Outline — a color-coded scene map of your drafted manuscript.** A new **Reverse Outline** view (linked from the series page) reads the finished/drafted manuscript and lays out what's *actually on the page*: it identifies the recurring plotlines (A-plot, subplots, POV threads) and segments the prose into scenes, each tagged to the plotline it advances — then shows them as a grid (rows = plotlines, columns = scenes in reading order) so you can see thread cadence, gaps, and tangles at a glance. Click any scene marker to read its summary, POV, setting, character list, and narrative/action/dialogue mix, and jump straight into the manuscript editor at that scene's issue. Generation streams live progress; the outline flags itself **stale** once the manuscript changes so you know to regenerate. This scene segmentation is the shared substrate upcoming editorial checks (scene balance, POV justification, cliffhangers, arc transitions) will read rather than re-deriving. (#1286)
- **Editorial checks — an extensible editorial-review system for the series pipeline.** Editorial rules (name confusability, exposition dumps, and more to come) previously had no shared home — each was a one-off. A new **editorial check registry + runner** lets each rule plug in, declare what it examines, and emit findings into the same manuscript-review comment set you already work through in the editor (jump-to, AI fix, accept/dismiss). This first release ships two reference checks: **Character name dissimilarity** (flags character names a reader could confuse — sharing a first letter, length, vowel pattern, opening, or ending) and **Info-dumping** (flags "as-you-know-Bob" exposition — backstory bricks, maid-and-butler dialogue, front-loaded world rules — with a suggestion to dramatize or trim each). Each check can be enabled/disabled and configured, and runs on demand for a series (with live progress) or automatically as part of Series Autopilot's editorial pass. Findings are tagged by which check raised them, so re-running never duplicates them and a dismissal stays dismissed for that check. New endpoints: `GET/PATCH /api/pipeline/editorial/checks` (catalog + enable/config) and `POST /api/pipeline/series/:id/editorial/checks/run` (run + SSE progress). (#1284)
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index 14382c7240..9037ab33b5 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -276,7 +276,9 @@ export default function CanonCard({
// CanonCard reveals an Expand → CharacterDetailEditor section and a
// Reference Sheet panel. NounsStage (series view) omits this so the
// per-series cast list stays focused on naming + visual refs.
- // Shape: { universeId, onExpandCharacter, expanding, onSheetCompleted, onSheetDeleted }
+ // Shape: { universeId, onExpandCharacter, expanding, onSheetCompleted, onSheetDeleted, castList }
+ // `castList` (the universe-wide character list) feeds the relationship-link
+ // target picker in CharacterDetailEditor (#1287).
characterExtensions = null,
}) {
const description = kind.descFor(entry);
@@ -395,6 +397,7 @@ export default function CanonCard({
<CharacterDetailsToggle>
<CharacterDetailEditor
entry={entry}
+ characters={characterExtensions.castList || []}
onPatch={(patch) => onPatchEntry(entry.id, patch)}
onExpand={characterExtensions.onExpandCharacter ? () => characterExtensions.onExpandCharacter(entry.id) : null}
expanding={!!characterExtensions.expanding}
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsx
index 6556e08d6c..8ffb45b130 100644
--- a/client/src/components/universe/CharacterDetailEditor.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.jsx
@@ -13,7 +13,7 @@
import { useState } from 'react';
import {
ChevronDown, ChevronRight, Plus, Trash2, WandSparkles, Loader2,
- Palette, Hand, Smile, Package, BookOpen, Eye, Activity,
+ Palette, Hand, Smile, Package, BookOpen, Eye, Activity, Users, Swords,
} from 'lucide-react';
import { BIBLE_LIMITS as L } from '../../lib/bibleLimits';
import useFieldDraft from '../../hooks/useFieldDraft';
@@ -55,6 +55,17 @@ const SECTIONS = Object.freeze([
},
]);
+// Mirrors `RELATIONSHIP_LINK_TYPES` / `RELATIONSHIP_OPPOSITION_AXES` in
+// server/lib/storyBible.js (#1287). The server sanitizer coerces an
+// unrecognized value to 'custom', so adding a token here without the server
+// side just means the UI offers a value the server folds back to custom.
+const RELATIONSHIP_LINK_TYPES = Object.freeze([
+ 'ally', 'antagonist', 'rival', 'mentor', 'love-interest', 'family', 'custom',
+]);
+const RELATIONSHIP_OPPOSITION_AXES = Object.freeze([
+ 'winner/loser', 'smart/dumb', 'hunter/prey', 'predator/prey', 'custom',
+]);
+
const LIST_SECTIONS = Object.freeze([
{
key: 'stats', label: 'Stats', icon: Activity, field: 'stats',
@@ -255,7 +266,177 @@ function ListSectionEditor({ section, entry, onPatchList, disabled }) {
);
}
-export default function CharacterDetailEditor({ entry, onPatch, onExpand, expanding = false, disabled = false }) {
+const REL_SELECT_CLASS = 'flex-1 min-w-0 px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50';
+const REL_INPUT_CLASS = 'w-full px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50';
+
+// Opposing-force editor (#1287) — only mounted when a link carries an
+// `opposition`, so its draft hooks stay consistent across renders. Captures the
+// binary tension (axis + the two roles) the reader watches to see reverse.
+function OppositionEditor({ idx, opposition, onChange, disabled }) {
+ const thisRole = useFieldDraft(opposition.thisRole || '', (v) => onChange({ thisRole: v }));
+ const targetRole = useFieldDraft(opposition.targetRole || '', (v) => onChange({ targetRole: v }));
+ const note = useFieldDraft(opposition.note || '', (v) => onChange({ note: v }));
+ const axisId = `rel-opp-axis-${idx}`;
+ return (
+ <div className="rounded border border-port-warning/40 bg-port-warning/5 p-1.5 space-y-1.5">
+ <div className="flex items-center gap-1.5">
+ <Swords size={11} className="text-port-warning" />
+ <label htmlFor={axisId} className="text-[10px] uppercase tracking-wider text-port-warning">Opposing force</label>
+ </div>
+ <select
+ id={axisId}
+ value={RELATIONSHIP_OPPOSITION_AXES.includes(opposition.axis) ? opposition.axis : 'custom'}
+ onChange={(e) => onChange({ axis: e.target.value })}
+ disabled={disabled}
+ className={REL_INPUT_CLASS}
+ >
+ {RELATIONSHIP_OPPOSITION_AXES.map((a) => <option key={a} value={a}>{a}</option>)}
+ </select>
+ <div className="flex gap-1.5">
+ <input
+ type="text" value={thisRole.value} onChange={thisRole.onChange} onBlur={thisRole.onBlur}
+ placeholder="this role (e.g. hunter)" maxLength={L.RELATIONSHIP_OPPOSITION_ROLE_MAX}
+ disabled={disabled} aria-label={`opposition ${idx + 1} this role`}
+ className={REL_SELECT_CLASS}
+ />
+ <input
+ type="text" value={targetRole.value} onChange={targetRole.onChange} onBlur={targetRole.onBlur}
+ placeholder="their role (e.g. prey)" maxLength={L.RELATIONSHIP_OPPOSITION_ROLE_MAX}
+ disabled={disabled} aria-label={`opposition ${idx + 1} target role`}
+ className={REL_SELECT_CLASS}
+ />
+ </div>
+ <input
+ type="text" value={note.value} onChange={note.onChange} onBlur={note.onBlur}
+ placeholder="reader is waiting to see if these reverse" maxLength={L.RELATIONSHIP_OPPOSITION_NOTE_MAX}
+ disabled={disabled} aria-label={`opposition ${idx + 1} note`}
+ className={REL_INPUT_CLASS}
+ />
+ </div>
+ );
+}
+
+// One relationship link row — target + type selects, prose description, and an
+// optional opposing-force block. The whole `relationshipLinks` array is patched
+// on every mutation (mirrors the list-section onPatchList contract); text
+// fields buffer via useFieldDraft and commit on blur.
+function RelationshipRow({ link, idx, others, onUpdate, onRemove, disabled }) {
+ const desc = useFieldDraft(link.description || '', (v) => onUpdate({ description: v }));
+ const hasOpposition = !!link.opposition;
+ const toggleOpposition = () => onUpdate({
+ opposition: hasOpposition ? null : { axis: 'custom', thisRole: '', targetRole: '', note: '' },
+ });
+ return (
+ <div className={`rounded border ${hasOpposition ? 'border-port-warning/40' : 'border-port-border'} bg-port-bg/40 p-2 space-y-1.5`}>
+ <div className="flex items-center gap-1.5">
+ <select
+ value={link.targetCharacterId || ''}
+ onChange={(e) => onUpdate({ targetCharacterId: e.target.value })}
+ disabled={disabled}
+ aria-label={`relationship ${idx + 1} target character`}
+ className={REL_SELECT_CLASS}
+ >
+ {others.map((c) => <option key={c.id} value={c.id}>{c.name || c.id}</option>)}
+ </select>
+ <select
+ value={RELATIONSHIP_LINK_TYPES.includes(link.type) ? link.type : 'custom'}
+ onChange={(e) => onUpdate({ type: e.target.value })}
+ disabled={disabled}
+ aria-label={`relationship ${idx + 1} type`}
+ className="w-28 shrink-0 px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50"
+ >
+ {RELATIONSHIP_LINK_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
+ </select>
+ <button
+ type="button" onClick={onRemove} disabled={disabled}
+ title="Remove relationship" aria-label={`remove relationship ${idx + 1}`}
+ className="shrink-0 text-gray-500 hover:text-port-error disabled:opacity-30"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ <input
+ type="text" value={desc.value} onChange={desc.onChange} onBlur={desc.onBlur}
+ placeholder="how they're connected and the tenor of the connection"
+ maxLength={L.RELATIONSHIP_DESCRIPTION_MAX} disabled={disabled}
+ aria-label={`relationship ${idx + 1} description`}
+ className={REL_INPUT_CLASS}
+ />
+ <button
+ type="button" onClick={toggleOpposition} disabled={disabled}
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border disabled:opacity-40 ${
+ hasOpposition
+ ? 'border-port-warning/50 text-port-warning hover:bg-port-warning/10'
+ : 'border-port-border text-gray-400 hover:text-white hover:border-gray-500'
+ }`}
+ >
+ <Swords size={10} /> {hasOpposition ? 'Remove opposing force' : 'Tag opposing force'}
+ </button>
+ {hasOpposition ? (
+ <OppositionEditor
+ idx={idx}
+ opposition={link.opposition}
+ onChange={(patch) => onUpdate({ opposition: { ...link.opposition, ...patch } })}
+ disabled={disabled}
+ />
+ ) : null}
+ </div>
+ );
+}
+
+// Relationships section — structured character-to-character links + opposing
+// forces (#1287). Needs the sibling cast (`characters`) to populate the target
+// picker; renders a prompt to add more cast when the character is the only one.
+function RelationshipsSection({ entry, characters, onPatch, disabled }) {
+ const links = Array.isArray(entry.relationshipLinks) ? entry.relationshipLinks : [];
+ const others = (Array.isArray(characters) ? characters : []).filter((c) => c?.id && c.id !== entry.id);
+ const commit = (next) => onPatch?.({ relationshipLinks: next });
+ const addLink = () => {
+ if (!others.length) return;
+ commit([...links, { targetCharacterId: others[0].id, type: 'custom', description: '' }]);
+ };
+ const updateLink = (idx, patch) => commit(links.map((l, i) => (i === idx ? { ...l, ...patch } : l)));
+ const removeLink = (idx) => commit(links.filter((_, i) => i !== idx));
+ const oppositionCount = links.filter((l) => l.opposition?.axis).length;
+ const summary = links.length === 0
+ ? 'empty'
+ : `${links.length} link${links.length === 1 ? '' : 's'}${oppositionCount ? ` · ${oppositionCount} opposing` : ''}`;
+ return (
+ <CollapsibleSection icon={Users} label="Relationships" summary={summary}>
+ {others.length === 0 ? (
+ <p className="text-[11px] text-gray-500 italic">Add another character to the cast to link relationships.</p>
+ ) : (
+ <>
+ {links.length === 0 ? (
+ <p className="text-[11px] text-gray-500 italic">No relationships yet.</p>
+ ) : (
+ <div className="space-y-2">
+ {links.map((link, idx) => (
+ <RelationshipRow
+ key={link.id || `rel-${idx}`}
+ link={link}
+ idx={idx}
+ others={others}
+ onUpdate={(patch) => updateLink(idx, patch)}
+ onRemove={() => removeLink(idx)}
+ disabled={disabled}
+ />
+ ))}
+ </div>
+ )}
+ <button
+ type="button" onClick={addLink} disabled={disabled}
+ 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 relationship
+ </button>
+ </>
+ )}
+ </CollapsibleSection>
+ );
+}
+
+export default function CharacterDetailEditor({ entry, onPatch, onExpand, expanding = false, disabled = false, characters = [] }) {
if (!entry) return null;
const patchField = (name, value) => onPatch?.({ [name]: value });
@@ -311,6 +492,13 @@ export default function CharacterDetailEditor({ entry, onPatch, onExpand, expand
</CollapsibleSection>
))}
+ <RelationshipsSection
+ entry={entry}
+ characters={characters}
+ onPatch={onPatch}
+ disabled={disabled}
+ />
+
{LIST_SECTIONS.map((section) => (
<ListSectionEditor
key={section.key}
diff --git a/client/src/components/universe/CharacterDetailEditor.test.jsx b/client/src/components/universe/CharacterDetailEditor.test.jsx
new file mode 100644
index 0000000000..83eeacd398
--- /dev/null
+++ b/client/src/components/universe/CharacterDetailEditor.test.jsx
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import CharacterDetailEditor from './CharacterDetailEditor';
+
+// Mock VoicePicker — it pulls in the voice API/socket layer the relationship
+// tests don't care about.
+vi.mock('../voice/VoicePicker', () => ({ default: () => null }));
+
+const ARIA = { id: 'chr-aria', name: 'Aria' };
+const BRAM = { id: 'chr-bram', name: 'Bram' };
+const CASS = { id: 'chr-cass', name: 'Cass' };
+
+// CollapsibleSection starts closed — open the Relationships one by clicking its
+// header button.
+const openRelationships = () => {
+ fireEvent.click(screen.getByRole('button', { name: /Relationships/i }));
+};
+
+describe('CharacterDetailEditor — Relationships (#1287)', () => {
+ it('prompts to add more cast when there are no other characters', () => {
+ render(<CharacterDetailEditor entry={ARIA} characters={[ARIA]} onPatch={() => {}} />);
+ openRelationships();
+ expect(screen.getByText(/Add another character to the cast/i)).toBeInTheDocument();
+ });
+
+ it('adds a link defaulting to the first other character + custom type', () => {
+ const onPatch = vi.fn();
+ render(<CharacterDetailEditor entry={ARIA} characters={[ARIA, BRAM, CASS]} onPatch={onPatch} />);
+ openRelationships();
+ fireEvent.click(screen.getByRole('button', { name: /Add relationship/i }));
+ expect(onPatch).toHaveBeenCalledWith({
+ relationshipLinks: [{ targetCharacterId: 'chr-bram', type: 'custom', description: '' }],
+ });
+ });
+
+ it('renders an existing link with target + type selects', () => {
+ const entry = {
+ ...ARIA,
+ relationshipLinks: [{ id: 'rel-1', targetCharacterId: 'chr-bram', type: 'ally' }],
+ };
+ render(<CharacterDetailEditor entry={entry} characters={[ARIA, BRAM]} onPatch={() => {}} />);
+ openRelationships();
+ const target = screen.getByRole('combobox', { name: /relationship 1 target character/i });
+ expect(target).toHaveValue('chr-bram');
+ const type = screen.getByRole('combobox', { name: /relationship 1 type/i });
+ expect(type).toHaveValue('ally');
+ });
+
+ it('patches the type when the type select changes', () => {
+ const onPatch = vi.fn();
+ const entry = {
+ ...ARIA,
+ relationshipLinks: [{ id: 'rel-1', targetCharacterId: 'chr-bram', type: 'ally' }],
+ };
+ render(<CharacterDetailEditor entry={entry} characters={[ARIA, BRAM]} onPatch={onPatch} />);
+ openRelationships();
+ fireEvent.change(screen.getByRole('combobox', { name: /relationship 1 type/i }), {
+ target: { value: 'rival' },
+ });
+ expect(onPatch).toHaveBeenCalledWith({
+ relationshipLinks: [{ id: 'rel-1', targetCharacterId: 'chr-bram', type: 'rival' }],
+ });
+ });
+
+ it('tags an opposing force, surfacing the axis editor', () => {
+ const onPatch = vi.fn();
+ const entry = {
+ ...ARIA,
+ relationshipLinks: [{ id: 'rel-1', targetCharacterId: 'chr-bram', type: 'antagonist' }],
+ };
+ render(<CharacterDetailEditor entry={entry} characters={[ARIA, BRAM]} onPatch={onPatch} />);
+ openRelationships();
+ fireEvent.click(screen.getByRole('button', { name: /Tag opposing force/i }));
+ expect(onPatch).toHaveBeenCalledWith({
+ relationshipLinks: [{
+ id: 'rel-1',
+ targetCharacterId: 'chr-bram',
+ type: 'antagonist',
+ opposition: { axis: 'custom', thisRole: '', targetRole: '', note: '' },
+ }],
+ });
+ });
+
+ it('shows the opposition count in the collapsed summary', () => {
+ const entry = {
+ ...ARIA,
+ relationshipLinks: [
+ { id: 'rel-1', targetCharacterId: 'chr-bram', opposition: { axis: 'hunter/prey' } },
+ { id: 'rel-2', targetCharacterId: 'chr-cass' },
+ ],
+ };
+ render(<CharacterDetailEditor entry={entry} characters={[ARIA, BRAM, CASS]} onPatch={() => {}} />);
+ // Summary renders inside the collapsed header.
+ expect(screen.getByText(/2 links · 1 opposing/i)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index 8242f1a268..4aa23e6b62 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -874,8 +874,12 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende
// per-card memoization and isn't worth the complexity at typical cast
// sizes.
const characterExtensions = useMemo(
- () => (kind.key === 'characters' ? { universeId, onExpandCharacter, onSheetCompleted, onSheetDeleted } : null),
- [kind.key, universeId, onExpandCharacter, onSheetCompleted, onSheetDeleted],
+ () => (kind.key === 'characters'
+ // `castList` is the universe-wide character list — feeds the
+ // relationship-link target picker in CharacterDetailEditor (#1287).
+ ? { universeId, onExpandCharacter, onSheetCompleted, onSheetDeleted, castList: fullList }
+ : null),
+ [kind.key, universeId, onExpandCharacter, onSheetCompleted, onSheetDeleted, fullList],
);
const Icon = kind.icon;
diff --git a/client/src/lib/bibleLimits.js b/client/src/lib/bibleLimits.js
index 7ef9453bc5..a20ac62c09 100644
--- a/client/src/lib/bibleLimits.js
+++ b/client/src/lib/bibleLimits.js
@@ -27,6 +27,12 @@ export const BIBLE_LIMITS = Object.freeze({
DISLIKES_MAX: 1500,
MANNERISMS_MAX: 1500,
RELATIONSHIPS_MAX: 2000,
+ RELATIONSHIP_TARGET_ID_MAX: 64,
+ RELATIONSHIP_DESCRIPTION_MAX: 1000,
+ RELATIONSHIP_OPPOSITION_AXIS_MAX: 60,
+ RELATIONSHIP_OPPOSITION_ROLE_MAX: 120,
+ RELATIONSHIP_OPPOSITION_NOTE_MAX: 600,
+ RELATIONSHIP_LINKS_PER_CHARACTER_MAX: 40,
SKILLS_MAX: 2000,
STAT_LABEL_MAX: 80,
STAT_VALUE_MAX: 200,
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 97bbcd0b6c..5aac9897d7 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -120,6 +120,130 @@ export const EDITORIAL_CHECKS = [
return findings;
},
},
+ {
+ id: 'relationships.reciprocity',
+ label: 'Relationship reciprocity',
+ description:
+ 'Flags one-sided structured relationship links — character A links to B, but B has no link back to A.',
+ scope: 'series',
+ kind: 'deterministic',
+ category: 'continuity',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ configSchema: z.object({}),
+ run: (ctx) => {
+ const chars = (ctx.canon?.characters || []).filter((c) => c && c.id);
+ const nameById = new Map(chars.map((c) => [c.id, c.name || c.id]));
+ // For O(1) "does B link back to A?" lookups, index every link as a
+ // "<source>→<target>" pair key.
+ const linkPairs = new Set();
+ for (const c of chars) {
+ for (const link of (Array.isArray(c.relationshipLinks) ? c.relationshipLinks : [])) {
+ if (link?.targetCharacterId) linkPairs.add(`${c.id}→${link.targetCharacterId}`);
+ }
+ }
+ const findings = [];
+ for (const c of chars) {
+ for (const link of (Array.isArray(c.relationshipLinks) ? c.relationshipLinks : [])) {
+ const targetId = link?.targetCharacterId;
+ // A dangling target (B doesn't exist) is the dangling-target check's
+ // job; reciprocity only speaks to links between two real characters.
+ if (!targetId || !nameById.has(targetId)) continue;
+ if (linkPairs.has(`${targetId}→${c.id}`)) continue;
+ const aName = nameById.get(c.id);
+ const bName = nameById.get(targetId);
+ findings.push({
+ severity: ctx.severityDefault,
+ category: 'continuity',
+ location: `Characters: ${aName} → ${bName}`,
+ problem: `"${aName}" has a ${link.type || 'custom'} link to "${bName}", but "${bName}" has no link back to "${aName}".`,
+ suggestion: `Add a reciprocal relationship link from "${bName}" to "${aName}" (or remove the one-sided link if it's intentional).`,
+ anchorQuote: aName,
+ issueNumber: null,
+ });
+ }
+ }
+ return findings;
+ },
+ },
+ {
+ id: 'relationships.dangling-target',
+ label: 'Relationship dangling target',
+ description:
+ 'Flags structured relationship links that point at a character id no longer present in the canon (deleted or renamed away).',
+ scope: 'series',
+ kind: 'deterministic',
+ category: 'continuity',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ configSchema: z.object({}),
+ run: (ctx) => {
+ const chars = (ctx.canon?.characters || []).filter((c) => c && c.id);
+ const idSet = new Set(chars.map((c) => c.id));
+ const nameById = new Map(chars.map((c) => [c.id, c.name || c.id]));
+ const findings = [];
+ for (const c of chars) {
+ for (const link of (Array.isArray(c.relationshipLinks) ? c.relationshipLinks : [])) {
+ const targetId = link?.targetCharacterId;
+ if (!targetId || idSet.has(targetId)) continue;
+ const aName = nameById.get(c.id);
+ findings.push({
+ severity: ctx.severityDefault,
+ category: 'continuity',
+ location: `Character: ${aName}`,
+ problem: `"${aName}" has a ${link.type || 'custom'} relationship link pointing at a character id (${targetId}) that no longer exists in the canon.`,
+ suggestion: 'Re-point the link at an existing character, or delete the stale link.',
+ anchorQuote: aName,
+ issueNumber: null,
+ });
+ }
+ }
+ return findings;
+ },
+ },
+ {
+ id: 'relationships.opposition-reversal',
+ label: 'Opposition role-reversal payoff',
+ description:
+ 'Advisory — surfaces every tagged opposing-force pair (hunter/prey, winner/loser…) so you can confirm whether the reader ever sees the roles reverse, or deliberately not.',
+ scope: 'series',
+ kind: 'deterministic',
+ category: 'arc',
+ severityDefault: 'low',
+ defaultEnabled: false,
+ configSchema: z.object({}),
+ run: (ctx) => {
+ const chars = (ctx.canon?.characters || []).filter((c) => c && c.id);
+ const nameById = new Map(chars.map((c) => [c.id, c.name || c.id]));
+ const findings = [];
+ // Dedupe by the unordered character pair so a reciprocally-tagged
+ // opposition (A→B and B→A both carry an axis) surfaces once, not twice.
+ const seenPairs = new Set();
+ for (const c of chars) {
+ for (const link of (Array.isArray(c.relationshipLinks) ? c.relationshipLinks : [])) {
+ const targetId = link?.targetCharacterId;
+ if (!targetId || !link.opposition?.axis || !nameById.has(targetId)) continue;
+ const pairKey = [c.id, targetId].sort().join('|');
+ if (seenPairs.has(pairKey)) continue;
+ seenPairs.add(pairKey);
+ const aName = nameById.get(c.id);
+ const bName = nameById.get(targetId);
+ const { axis, thisRole, targetRole } = link.opposition;
+ const roles = thisRole && targetRole ? ` (${aName}: ${thisRole}, ${bName}: ${targetRole})` : '';
+ findings.push({
+ severity: ctx.severityDefault,
+ category: 'arc',
+ location: `Characters: ${aName} / ${bName}`,
+ problem: `Opposing-force pair tagged on "${aName}" / "${bName}" — axis "${axis}"${roles}.`,
+ suggestion: 'Confirm the reader sees these roles reverse at some point in the arc (or that holding them fixed is the intended payoff).',
+ anchorQuote: aName,
+ issueNumber: null,
+ });
+ }
+ }
+ return findings;
+ },
+ },
{
id: 'prose.info-dumping',
label: 'Info-dumping / "as you know, Bob" exposition',
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index b4879744b6..70c9895e9e 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -215,3 +215,91 @@ describe('naming.dissimilar-names — deterministic check', () => {
expect(run([{}, { name: '' }])).toEqual([]);
});
});
+
+describe('relationships.reciprocity — deterministic check', () => {
+ const run = (characters) =>
+ getCheck('relationships.reciprocity').run({ canon: { characters }, config: {}, severityDefault: 'low' });
+
+ it('flags a one-sided link', () => {
+ const findings = run([
+ { id: 'a', name: 'Aria', relationshipLinks: [{ targetCharacterId: 'b', type: 'ally' }] },
+ { id: 'b', name: 'Bram', relationshipLinks: [] },
+ ]);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('continuity');
+ expect(findings[0].problem).toMatch(/no link back/i);
+ });
+
+ it('does not flag a reciprocated pair', () => {
+ const findings = run([
+ { id: 'a', name: 'Aria', relationshipLinks: [{ targetCharacterId: 'b' }] },
+ { id: 'b', name: 'Bram', relationshipLinks: [{ targetCharacterId: 'a' }] },
+ ]);
+ expect(findings).toEqual([]);
+ });
+
+ it('ignores links to nonexistent characters (the dangling-target check owns those)', () => {
+ const findings = run([
+ { id: 'a', name: 'Aria', relationshipLinks: [{ targetCharacterId: 'ghost' }] },
+ ]);
+ expect(findings).toEqual([]);
+ });
+
+ it('tolerates empty / link-less canon', () => {
+ expect(run([])).toEqual([]);
+ expect(run([{ id: 'a', name: 'Aria' }])).toEqual([]);
+ });
+});
+
+describe('relationships.dangling-target — deterministic check', () => {
+ const run = (characters) =>
+ getCheck('relationships.dangling-target').run({ canon: { characters }, config: {}, severityDefault: 'medium' });
+
+ it('flags a link pointing at a missing character id', () => {
+ const findings = run([
+ { id: 'a', name: 'Aria', relationshipLinks: [{ targetCharacterId: 'deleted-id', type: 'rival' }] },
+ ]);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].problem).toMatch(/no longer exists/i);
+ expect(findings[0].problem).toContain('deleted-id');
+ });
+
+ it('does not flag a link to an existing character', () => {
+ const findings = run([
+ { id: 'a', name: 'Aria', relationshipLinks: [{ targetCharacterId: 'b' }] },
+ { id: 'b', name: 'Bram' },
+ ]);
+ expect(findings).toEqual([]);
+ });
+
+ it('tolerates empty canon', () => {
+ expect(run([])).toEqual([]);
+ });
+});
+
+describe('relationships.opposition-reversal — deterministic advisory', () => {
+ const run = (characters) =>
+ getCheck('relationships.opposition-reversal').run({ canon: { characters }, config: {}, severityDefault: 'low' });
+
+ it('surfaces a tagged opposition pair once (deduped across reciprocal links)', () => {
+ const findings = run([
+ { id: 'a', name: 'Aria', relationshipLinks: [{ targetCharacterId: 'b', opposition: { axis: 'hunter/prey', thisRole: 'hunter', targetRole: 'prey' } }] },
+ { id: 'b', name: 'Bram', relationshipLinks: [{ targetCharacterId: 'a', opposition: { axis: 'hunter/prey', thisRole: 'prey', targetRole: 'hunter' } }] },
+ ]);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('arc');
+ expect(findings[0].problem).toMatch(/hunter\/prey/);
+ });
+
+ it('does not surface links without an opposition tag', () => {
+ const findings = run([
+ { id: 'a', name: 'Aria', relationshipLinks: [{ targetCharacterId: 'b', type: 'ally' }] },
+ { id: 'b', name: 'Bram' },
+ ]);
+ expect(findings).toEqual([]);
+ });
+
+ it('is disabled by default (advisory)', () => {
+ expect(getCheck('relationships.opposition-reversal').defaultEnabled).toBe(false);
+ });
+});
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 07d50af3bf..8fe94676bd 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -35,7 +35,16 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// Type-level (storage layout) version for `data/universes/{id}/index.json`.
// v5 = post-split. Migration 034 introduced it. The per-record-shape version
// stays at 4 (stamped inside each record by `sanitizeTemplate`).
- universes: 5,
+ // v6 = canon characters gained `relationshipLinks[]` (structured
+ // character-to-character links + opposing-force tags, #1287). Additive +
+ // gracefully degrading, but version-gated for the same reason as
+ // `pipelineIssues`/`pipelineSeries` v2: a not-yet-upgraded peer that receives
+ // and re-sanitizes a universe through its relationshipLinks-unaware
+ // `sanitizeCharacter` would silently strip the field and last-writer-wins the
+ // loss back onto the newer peer. Bumping makes the older peer reject the
+ // ahead-version universe transfer instead. Per-category gate → only universe
+ // sync pauses with old peers; pipeline/catalog/etc keep flowing.
+ universes: 6,
// 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 74921e0e55..d777d09c26 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -18,7 +18,9 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
// If this changes, the corresponding migration in scripts/migrations/
// must ship alongside it. The test exists to make a layout bump a
// deliberate two-file edit.
- expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(5);
+ // v6 = canon characters gained relationshipLinks[] (#1287); additive +
+ // version-gated so an older peer can't strip-then-LWW the field back.
+ expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(6);
});
it('declares pipeline collection layout versions', () => {
@@ -37,14 +39,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(5);
+ expect(meta.schemaVersions.universes).toBe(6);
expect(meta.schemaVersions.pipelineIssues).toBe(2);
expect(meta.schemaVersions.pipelineSeries).toBe(2);
});
it('overrides merge into schemaVersions', async () => {
const meta = await buildPortosMeta({ schemaVersions: { future: 1 } });
- expect(meta.schemaVersions.universes).toBe(5);
+ expect(meta.schemaVersions.universes).toBe(6);
expect(meta.schemaVersions.future).toBe(1);
});
});
@@ -192,7 +194,7 @@ 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: 5, pipelineSeries: 2, pipelineIssues: 2, mediaCollections: 2 },
+ { universes: 6, pipelineSeries: 2, pipelineIssues: 2, 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 ccd09c83b7..1d81b4ae1b 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -49,6 +49,16 @@ export const BIBLE_LIMITS = Object.freeze({
DISLIKES_MAX: 1500,
MANNERISMS_MAX: 1500,
RELATIONSHIPS_MAX: 2000,
+ // Structured character-to-character relationship links (#1287). The legacy
+ // prose `relationships` field above stays; `relationshipLinks[]` is additive.
+ // `description` is per-link prose; `opposition` captures a binary-tension
+ // axis (hunter/prey, winner/loser…) the reader watches to see reverse.
+ RELATIONSHIP_TARGET_ID_MAX: 64,
+ RELATIONSHIP_DESCRIPTION_MAX: 1000,
+ RELATIONSHIP_OPPOSITION_AXIS_MAX: 60,
+ RELATIONSHIP_OPPOSITION_ROLE_MAX: 120,
+ RELATIONSHIP_OPPOSITION_NOTE_MAX: 600,
+ RELATIONSHIP_LINKS_PER_CHARACTER_MAX: 40,
SKILLS_MAX: 2000,
// Flexible stats list — open key/value so non-humans aren't forced into
// human anatomy ("Number of eyes: 8", "Form: spectral vapor", etc).
@@ -128,6 +138,22 @@ export const BIBLE_KIND = Object.freeze({
OBJECT: 'object',
});
+// Structured relationship-link taxonomy (#1287). `type` is the dynamic
+// between two characters; `custom` lets the writer name one the list misses
+// (the free-text `description` carries the specifics). `opposition.axis`
+// tags a binary-force tension (hunter/prey, winner/loser…) the reader tracks
+// to see whether the roles ever reverse. Both default to `custom` on an
+// unrecognized value rather than dropping the link, so a legacy/peer payload
+// with a future type still round-trips (its prose description is preserved).
+export const RELATIONSHIP_LINK_TYPES = Object.freeze([
+ 'ally', 'antagonist', 'rival', 'mentor', 'love-interest', 'family', 'custom',
+]);
+export const RELATIONSHIP_OPPOSITION_AXES = Object.freeze([
+ 'winner/loser', 'smart/dumb', 'hunter/prey', 'predator/prey', 'custom',
+]);
+const RELATIONSHIP_LINK_TYPE_SET = new Set(RELATIONSHIP_LINK_TYPES);
+const RELATIONSHIP_OPPOSITION_AXIS_SET = new Set(RELATIONSHIP_OPPOSITION_AXES);
+
// Enums for the location-classification fields on Place canon entries.
// Mirrors AnyFilm's INT/EXT + time-of-day taxonomy so generated panels and
// scene starts inherit lighting/composition cues for free.
@@ -606,6 +632,45 @@ function sanitizeHandGesture(raw) {
return { id: ensureId(raw.id, 'gesture-'), name, description: trimTo(raw.description, BIBLE_LIMITS.GESTURE_DESC_MAX) };
}
+// Structured relationship link (#1287). Requires a `targetCharacterId` — a
+// link with nothing to point at is meaningless, so a blank target drops the
+// row (matches the name-required pattern in the other list sanitizers). `type`
+// and `opposition.axis` normalize an unrecognized value to `custom` rather
+// than dropping it, so a peer/legacy payload carrying a future enum value
+// still round-trips with its prose intact. `opposition` collapses to absent
+// unless an axis is present, and `locked` persists explicit true/false only.
+function sanitizeOpposition(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const axisRaw = trimTo(raw.axis, BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_AXIS_MAX);
+ if (!axisRaw) return null;
+ const axis = RELATIONSHIP_OPPOSITION_AXIS_SET.has(axisRaw) ? axisRaw : 'custom';
+ return {
+ axis,
+ thisRole: trimTo(raw.thisRole, BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_ROLE_MAX),
+ targetRole: trimTo(raw.targetRole, BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_ROLE_MAX),
+ note: trimTo(raw.note, BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_NOTE_MAX),
+ };
+}
+
+function sanitizeRelationshipLink(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const targetCharacterId = trimTo(raw.targetCharacterId, BIBLE_LIMITS.RELATIONSHIP_TARGET_ID_MAX);
+ if (!targetCharacterId) return null;
+ const typeRaw = trimTo(raw.type, BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_AXIS_MAX);
+ const type = RELATIONSHIP_LINK_TYPE_SET.has(typeRaw) ? typeRaw : 'custom';
+ const out = {
+ id: ensureId(raw.id, 'rel-'),
+ targetCharacterId,
+ type,
+ description: trimTo(raw.description, BIBLE_LIMITS.RELATIONSHIP_DESCRIPTION_MAX),
+ };
+ const opposition = sanitizeOpposition(raw.opposition);
+ if (opposition) out.opposition = opposition;
+ if (raw.locked === true) out.locked = true;
+ else if (raw.locked === false) out.locked = false;
+ return out;
+}
+
// Shared canon extras applied to every kind. Persists explicit `locked: true`
// AND `locked: false` so a Universe-Builder caller can flip the bit and have
// the change survive round-trips. Missing `locked` still collapses to absent
@@ -675,6 +740,14 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,
dislikes: trimTo(raw.dislikes, BIBLE_LIMITS.DISLIKES_MAX),
mannerisms: trimTo(raw.mannerisms, BIBLE_LIMITS.MANNERISMS_MAX),
relationships: trimTo(raw.relationships, BIBLE_LIMITS.RELATIONSHIPS_MAX),
+ // Structured character-to-character links + opposing-force tags (#1287).
+ // Additive to the legacy prose `relationships` field above. Empty array
+ // stays the legacy shape — every existing character keeps round-tripping.
+ relationshipLinks: sanitizeListWith(
+ raw.relationshipLinks,
+ sanitizeRelationshipLink,
+ BIBLE_LIMITS.RELATIONSHIP_LINKS_PER_CHARACTER_MAX,
+ ),
skills: trimTo(raw.skills, BIBLE_LIMITS.SKILLS_MAX),
notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),
// Flexible stats list. Open key/value so ghosts/spiders/clouds aren't
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index 4fc0a09700..dc13f8e444 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -291,6 +291,128 @@ describe('storyBible — sanitizeCharacter', () => {
});
});
+ describe('relationshipLinks (#1287)', () => {
+ it('defaults a missing relationshipLinks field to an empty array (legacy shape)', () => {
+ expect(sanitizeCharacter({ name: 'A' }).relationshipLinks).toEqual([]);
+ });
+
+ it('coerces a non-array relationshipLinks field to an empty array', () => {
+ expect(sanitizeCharacter({ name: 'A', relationshipLinks: 'nope' }).relationshipLinks).toEqual([]);
+ });
+
+ it('sanitizes a well-formed link + mints a rel- id when none supplied', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [{ targetCharacterId: 'chr-bob', type: 'ally', description: 'old friends' }],
+ });
+ expect(out.relationshipLinks).toHaveLength(1);
+ expect(out.relationshipLinks[0].id).toMatch(/^rel-/);
+ expect(out.relationshipLinks[0].targetCharacterId).toBe('chr-bob');
+ expect(out.relationshipLinks[0].type).toBe('ally');
+ expect(out.relationshipLinks[0].description).toBe('old friends');
+ expect(out.relationshipLinks[0].opposition).toBeUndefined();
+ });
+
+ it('preserves a supplied link id', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [{ id: 'rel-fixed-1', targetCharacterId: 'chr-bob' }],
+ });
+ expect(out.relationshipLinks[0].id).toBe('rel-fixed-1');
+ });
+
+ it('drops a link with no targetCharacterId', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [{ type: 'ally', description: 'dangling' }, { targetCharacterId: 'chr-bob' }],
+ });
+ expect(out.relationshipLinks).toHaveLength(1);
+ expect(out.relationshipLinks[0].targetCharacterId).toBe('chr-bob');
+ });
+
+ it('coerces an unrecognized type to custom (keeps the link + its prose)', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [{ targetCharacterId: 'chr-bob', type: 'frenemy', description: 'complicated' }],
+ });
+ expect(out.relationshipLinks[0].type).toBe('custom');
+ expect(out.relationshipLinks[0].description).toBe('complicated');
+ });
+
+ it('defaults a missing type to custom', () => {
+ const out = sanitizeCharacter({ name: 'A', relationshipLinks: [{ targetCharacterId: 'chr-bob' }] });
+ expect(out.relationshipLinks[0].type).toBe('custom');
+ });
+
+ it('sanitizes opposition + coerces an unrecognized axis to custom', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [{
+ targetCharacterId: 'chr-bob',
+ type: 'antagonist',
+ opposition: { axis: 'cat/mouse', thisRole: 'hunter', targetRole: 'prey', note: 'will it flip?' },
+ }],
+ });
+ const opp = out.relationshipLinks[0].opposition;
+ expect(opp.axis).toBe('custom');
+ expect(opp.thisRole).toBe('hunter');
+ expect(opp.targetRole).toBe('prey');
+ expect(opp.note).toBe('will it flip?');
+ });
+
+ it('keeps a recognized opposition axis verbatim', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [{ targetCharacterId: 'chr-bob', opposition: { axis: 'hunter/prey' } }],
+ });
+ expect(out.relationshipLinks[0].opposition.axis).toBe('hunter/prey');
+ });
+
+ it('drops an opposition with no axis (collapses to absent)', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [{ targetCharacterId: 'chr-bob', opposition: { thisRole: 'hunter' } }],
+ });
+ expect(out.relationshipLinks[0].opposition).toBeUndefined();
+ });
+
+ it('persists explicit locked true/false but drops a non-boolean', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [
+ { targetCharacterId: 'b', locked: true },
+ { targetCharacterId: 'c', locked: false },
+ { targetCharacterId: 'd', locked: 'yes' },
+ ],
+ });
+ expect(out.relationshipLinks[0].locked).toBe(true);
+ expect(out.relationshipLinks[1].locked).toBe(false);
+ expect(out.relationshipLinks[2].locked).toBeUndefined();
+ });
+
+ it('caps the list at RELATIONSHIP_LINKS_PER_CHARACTER_MAX', () => {
+ const tooMany = Array.from(
+ { length: BIBLE_LIMITS.RELATIONSHIP_LINKS_PER_CHARACTER_MAX + 5 },
+ (_, i) => ({ targetCharacterId: `chr-${i}` }),
+ );
+ const out = sanitizeCharacter({ name: 'A', relationshipLinks: tooMany });
+ expect(out.relationshipLinks).toHaveLength(BIBLE_LIMITS.RELATIONSHIP_LINKS_PER_CHARACTER_MAX);
+ });
+
+ it('clamps over-long description + opposition fields', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ relationshipLinks: [{
+ targetCharacterId: 'chr-bob',
+ description: 'x'.repeat(BIBLE_LIMITS.RELATIONSHIP_DESCRIPTION_MAX + 50),
+ opposition: { axis: 'hunter/prey', note: 'y'.repeat(BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_NOTE_MAX + 50) },
+ }],
+ });
+ expect(out.relationshipLinks[0].description.length).toBe(BIBLE_LIMITS.RELATIONSHIP_DESCRIPTION_MAX);
+ expect(out.relationshipLinks[0].opposition.note.length).toBe(BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_NOTE_MAX);
+ });
+ });
+
describe('extended character fields (novelist + graphic-novelist depth)', () => {
it('defaults every new string field to empty + every list field to []', () => {
const out = sanitizeCharacter({ name: 'Bare' });
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 7e7bca34e4..12cb51748b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -3,7 +3,7 @@ import { ServerError } from './errorHandler.js';
import { partialWithoutDefaults, emptyToUndefined, emptyToNull } 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 } from './storyBible.js';
+import { BIBLE_LIMITS, RELATIONSHIP_LINK_TYPES, RELATIONSHIP_OPPOSITION_AXES } from './storyBible.js';
import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
@@ -1085,6 +1085,25 @@ const wrWardrobeField = z.array(z.object({
createdAt: z.string().optional(),
updatedAt: z.string().optional(),
}).strict()).max(BIBLE_LIMITS.WARDROBES_PER_CHARACTER_MAX);
+// Structured relationship links (#1287). `id` is omitted on POSTs — the
+// sanitizer mints it. `type` / `opposition.axis` accept the known enum tokens;
+// an unrecognized value (legacy/peer payload) is coerced to `custom` by the
+// sanitizer, not rejected here, so older clients never 400. Limits sourced
+// from BIBLE_LIMITS so bumping a constant updates Zod automatically.
+const wrOppositionField = z.object({
+ axis: z.enum(RELATIONSHIP_OPPOSITION_AXES).or(z.string().trim().max(BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_AXIS_MAX)),
+ thisRole: z.string().max(BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_ROLE_MAX).optional(),
+ targetRole: z.string().max(BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_ROLE_MAX).optional(),
+ note: z.string().max(BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_NOTE_MAX).optional(),
+}).strict();
+const wrRelationshipLinksField = z.array(z.object({
+ id: z.string().trim().max(64).optional(),
+ targetCharacterId: z.string().trim().min(1).max(BIBLE_LIMITS.RELATIONSHIP_TARGET_ID_MAX),
+ type: z.enum(RELATIONSHIP_LINK_TYPES).or(z.string().trim().max(BIBLE_LIMITS.RELATIONSHIP_OPPOSITION_AXIS_MAX)).optional(),
+ description: z.string().max(BIBLE_LIMITS.RELATIONSHIP_DESCRIPTION_MAX).optional(),
+ opposition: wrOppositionField.nullable().optional(),
+ locked: z.boolean().optional(),
+}).strict()).max(BIBLE_LIMITS.RELATIONSHIP_LINKS_PER_CHARACTER_MAX);
export const writersRoomCharacterCreateSchema = z.object({
name: z.string().trim().min(1).max(200),
aliases: z.array(z.string().trim().min(1).max(200)).max(20).optional(),
@@ -1095,6 +1114,7 @@ export const writersRoomCharacterCreateSchema = z.object({
notes: wrCharTextField.optional(),
voiceId: wrVoiceIdField.optional(),
wardrobes: wrWardrobeField.optional(),
+ relationshipLinks: wrRelationshipLinksField.optional(),
}).strict();
export const writersRoomCharacterUpdateSchema = z.object({
name: z.string().trim().min(1).max(200).optional(),
@@ -1106,6 +1126,7 @@ export const writersRoomCharacterUpdateSchema = z.object({
notes: wrCharTextField.optional(),
voiceId: wrVoiceIdField.optional(),
wardrobes: wrWardrobeField.optional(),
+ relationshipLinks: wrRelationshipLinksField.optional(),
}).strict();
const wrPlaceTextField = z.string().max(2000);
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index a39c1e068d..03ed642c32 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -15,7 +15,8 @@ import {
createCosTaskSchema,
featureProviderConfigSchema,
codeReviewSettingsSchema,
- locationSettingsSchema
+ locationSettingsSchema,
+ writersRoomCharacterUpdateSchema
} from './validation.js';
describe('validation.js', () => {
@@ -791,4 +792,39 @@ describe('validation.js', () => {
expect(locationSettingsSchema.safeParse({ lat: 1, lon: 1, alt: 100 }).success).toBe(false);
});
});
+
+ describe('writersRoomCharacterUpdateSchema — relationshipLinks (#1287)', () => {
+ it('accepts a well-formed relationship link with opposition', () => {
+ const result = writersRoomCharacterUpdateSchema.safeParse({
+ relationshipLinks: [{
+ targetCharacterId: 'chr-bob',
+ type: 'antagonist',
+ description: 'mortal enemies',
+ opposition: { axis: 'hunter/prey', thisRole: 'hunter', targetRole: 'prey', note: 'will it flip?' },
+ }],
+ });
+ expect(result.success).toBe(true);
+ });
+
+ it('accepts a link with no id (server mints it) and a custom type', () => {
+ const result = writersRoomCharacterUpdateSchema.safeParse({
+ relationshipLinks: [{ targetCharacterId: 'chr-bob', type: 'frenemy' }],
+ });
+ expect(result.success).toBe(true);
+ });
+
+ it('rejects a link missing targetCharacterId', () => {
+ const result = writersRoomCharacterUpdateSchema.safeParse({
+ relationshipLinks: [{ type: 'ally' }],
+ });
+ expect(result.success).toBe(false);
+ });
+
+ it('rejects an unknown key inside a link (strict)', () => {
+ const result = writersRoomCharacterUpdateSchema.safeParse({
+ relationshipLinks: [{ targetCharacterId: 'chr-bob', bogus: true }],
+ });
+ expect(result.success).toBe(false);
+ });
+ });
});
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index d7ec49f5b4..c1b3f6be3f 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -156,19 +156,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(5);
+ expect(snap.portosMeta.schemaVersions.universes).toBe(6);
});
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: 6 } } });
+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 7 } } });
expect(result.applied).toBe(false);
expect(result.count).toBe(0);
expect(result.blockedBySchema).toBeDefined();
expect(result.blockedBySchema.ahead).toEqual([
- { category: 'universes', senderV: 6, receiverV: 5 },
+ { category: 'universes', senderV: 7, receiverV: 6 },
]);
expect(result.blockedBySchema.senderPortosVersion).toBe('99.0.0');
// Nothing was written.
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index bbd7012a53..bd2592be1c 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2202,7 +2202,7 @@ 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(5);
+ expect(manifest.portosSchemaVersions.universes).toBe(6);
});
it('importer rejects a manifest when the sender is AHEAD on a category the manifest CARRIES', async () => {
@@ -2214,7 +2214,7 @@ describe('sharing round-trip', () => {
// PortOS instance landing in an OLDER instance's bucket.
const manifestPath = join(tempBucket, 'manifests', exp.filename);
const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
- manifest.portosSchemaVersions = { universes: 5, pipelineSeries: 99, pipelineIssues: 1, mediaCollections: 1 };
+ manifest.portosSchemaVersions = { universes: 6, pipelineSeries: 99, pipelineIssues: 1, mediaCollections: 1 };
manifest.producedByVersion = '99.0.0';
writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
// Delete the local series so the auto-merge would normally re-create it.
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 8ec3ea0c6e..4c9f36f936 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -2487,17 +2487,17 @@ describe('peerSync', () => {
describe('receiver — applyIncomingPush', () => {
it('rejects when sender schemaVersions.universes is AHEAD of local code', async () => {
- // Local code is at universes:5 (see server/lib/schemaVersions.js).
- // A push from a sender on universes:6 must NOT touch local state.
+ // Local code is at universes:6 (see server/lib/schemaVersions.js).
+ // A push from a sender on universes:7 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: 6 } },
+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 7 } },
}).catch((err) => err);
expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');
- expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 6, receiverV: 5 }]);
+ expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 7, receiverV: 6 }]);
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
@@ -2516,7 +2516,7 @@ describe('peerSync', () => {
record: { id: 'u1', name: 'Foo' },
assetManifest: [],
sourceInstanceId: 'peer-a',
- portosMeta: { portosVersion: '2.7.0', schemaVersions: { universes: 5 } },
+ portosMeta: { portosVersion: '2.7.0', schemaVersions: { universes: 6 } },
});
expect(mergeUniversesFromSync).toHaveBeenCalledWith(
[expect.objectContaining({ id: 'u1' })],
@@ -2525,7 +2525,7 @@ describe('peerSync', () => {
});
it('passes through when sender is BEHIND local (sanitizer handles the backfill)', async () => {
- // Older peer pushes a v4-shape universe. Receiver is on v5 but the
+ // Older peer pushes a v4-shape universe. Receiver is on v6 but the
// record-shape sanitizer can backfill, so we apply rather than reject.
await applyIncomingPush({
kind: 'universe',
@@ -2710,7 +2710,7 @@ describe('peerSync', () => {
expect(call).toBeDefined();
const body = JSON.parse(call[1].body);
expect(body.portosMeta).toBeDefined();
- expect(body.portosMeta.schemaVersions.universes).toBe(5);
+ expect(body.portosMeta.schemaVersions.universes).toBe(6);
expect(typeof body.portosMeta.portosVersion).toBe('string');
});
diff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.js
index d781265e96..1587c21038 100644
--- a/server/services/universeCharacterExpand.js
+++ b/server/services/universeCharacterExpand.js
@@ -28,6 +28,10 @@ const STRING_FIELDS = Object.freeze([
const LIST_FIELDS = Object.freeze([
'stats', 'colorPalette', 'props', 'expressions', 'handGestures',
]);
+// `relationshipLinks` (#1287) is INTENTIONALLY excluded from both lists: each
+// link points at a sibling character by `targetCharacterId`, an id the LLM
+// expand call has no way to produce. The `{ ...target }` spread above
+// preserves any existing links untouched; the writer authors them in the UI.
// Distinct from universeCanon's peerForPrompt: the expand prompt benefits from
// the extended visual / theme fields for richer distinctness signals.