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: add universe art style references

[._.]/ Adam Eivy91c617cc05e7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 428bec50a0..f16a70d20b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,6 +5,10 @@
- **[issue-3061] Healthy agent-created pull requests now merge on the watcher tick instead of spending another agent lane** — when PortOS opens a GitHub PR with no review loop, the scheduled PR watcher now reads its CI and merge state: a clean PR whose checks are all green merges directly, while an actual validation failure or merge conflict still starts the same merge-only follow-up agent as before. PRs waiting on CI remain quiet for a bounded number of checks; if they never settle, PortOS stops polling them and posts a high-priority notice with a link to the PR.
- **[issue-3019] Layered Intelligence now notices when approved work is not being delivered** — its self-check now tracks approval-to-completion separately from reasoning-run success, so a loop that completes its own runs but repeatedly leaves approved proposals unfinished stops filing self-improvement work until delivery recovers. A five-approval floor keeps a fresh loop from being gated on cold-start noise, and the reasoner-facing notice identifies whether run health, delivery health, or both caused the guardrail.
+## Universes
+
+- **Upload an art reference to a universe bible and decide whether its style should shape the world** — a new Art style references section accepts an image from the gallery or your device, asks a vision-capable model for an editable title and recreation prompt, and previews the exact style-notes and positive/negative guidance diff before anything changes. You can keep the analyzed image as a reference without changing the guide, or adopt the proposed style and add the reference together in one save. References and their gallery images travel with the universe across supported sync peers.
+
## 3D
- **[issue-3033] 3D setup notices now stay in sync with each model's Hugging Face requirements** — the server now describes which gated repositories each image-to-3D target needs, so the 3D page, install guidance, and render-error help all draw from the same source. Adding a target with different (or no) gated dependencies no longer risks showing stale setup instructions.
diff --git a/client/src/components/universeBuilder/UniverseBibleTab.jsx b/client/src/components/universeBuilder/UniverseBibleTab.jsx
index 7d1a9a6d8a..00981a284c 100644
--- a/client/src/components/universeBuilder/UniverseBibleTab.jsx
+++ b/client/src/components/universeBuilder/UniverseBibleTab.jsx
@@ -14,6 +14,7 @@ import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip';
import StyleProbeImage from '../universe/StyleProbeImage';
import VisionProviderPicker from '../universe/VisionProviderPicker';
import InfluenceChipsInput from './InfluenceChipsInput';
+import UniverseStyleReferences from './UniverseStyleReferences';
function LockButton({ field, locked, onToggle, label }) {
const isLocked = !!locked?.[field];
@@ -107,6 +108,9 @@ export default function BibleTab({
onPreview,
onStyleProbeRenderComplete = null,
styleProbeDirty = false,
+ saved = false,
+ onPersistStyleReference,
+ onRemoveStyleReference,
}) {
const { providers, providerModels, providerLabel, activeProviderId } = llm;
const {
@@ -352,6 +356,12 @@ export default function BibleTab({
locked={draft.locked}
onToggleLock={toggleLock}
/>
+ <UniverseStyleReferences
+ universe={draft}
+ saved={saved}
+ onPersist={onPersistStyleReference}
+ onRemove={onRemoveStyleReference}
+ />
<div className="mt-4 pt-4 border-t border-port-border">
{/* StyleProbeImage persists styleImageRefs server-side itself; merge
only that field into the draft so unsaved style edits aren't lost.
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
index f4122ebe57..6d3bb7d943 100644
--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx
+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
@@ -139,7 +139,9 @@ export default function UniverseBuilder() {
providerLabel,
providerModels,
providers,
+ persistStyleReference,
removeCategory,
+ removeStyleReference,
runs,
saving,
setCanonDirty,
@@ -561,6 +563,9 @@ export default function UniverseBuilder() {
onPreview={openPreviewByFilename}
onStyleProbeRenderComplete={bumpGalleryRefresh}
styleProbeDirty={styleProbeDirty}
+ saved={!!selectedId}
+ onPersistStyleReference={persistStyleReference}
+ onRemoveStyleReference={removeStyleReference}
/>
)}
diff --git a/client/src/components/universeBuilder/UniverseStyleReferences.jsx b/client/src/components/universeBuilder/UniverseStyleReferences.jsx
new file mode 100644
index 0000000000..f73107eddb
--- /dev/null
+++ b/client/src/components/universeBuilder/UniverseStyleReferences.jsx
@@ -0,0 +1,282 @@
+import { useState } from 'react';
+import { ImagePlus, Loader2, Sparkles, Trash2, X } from 'lucide-react';
+import {
+ analyzeUniverseStyleReference,
+ WORLD_STYLE_REFERENCES_MAX,
+} from '../../services/api';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
+import Modal from '../ui/Modal';
+import toast from '../ui/Toast';
+import VisionProviderPicker from '../universe/VisionProviderPicker';
+
+const TITLE_MAX = 120;
+const PROMPT_MAX = 4000;
+
+function TokenDiff({ label, diff, tone }) {
+ if (!diff?.changed) return null;
+ const addedClass = tone === 'positive' ? 'text-port-success' : 'text-port-error';
+ return (
+ <div>
+ <div className="text-[11px] uppercase tracking-wide text-gray-500 mb-1">{label}</div>
+ <div className="flex flex-wrap gap-1">
+ {diff.removed.map((token) => (
+ <span key={`removed-${token}`} className="rounded bg-white/5 px-1.5 py-0.5 text-[11px] text-gray-500 line-through">
+ {token}
+ </span>
+ ))}
+ {diff.added.map((token) => (
+ <span key={`added-${token}`} className={`rounded bg-white/5 px-1.5 py-0.5 text-[11px] ${addedClass}`}>
+ + {token}
+ </span>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function StyleDiff({ analysis }) {
+ const diff = analysis?.diff;
+ if (!diff) return null;
+ return (
+ <section className="rounded-lg border border-port-border bg-port-bg/60 p-3 space-y-3">
+ <div>
+ <h3 className="text-sm font-medium text-white">Style guide preview</h3>
+ <p className="text-xs text-gray-500">
+ Review this diff before deciding whether the reference should update the universe.
+ </p>
+ </div>
+ {!diff.hasChanges ? (
+ <p className="text-xs text-gray-400">The current guidance already matches this reference.</p>
+ ) : null}
+ {diff.styleNotes?.changed ? (
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
+ <div>
+ <div className="text-[11px] uppercase tracking-wide text-gray-500 mb-1">Current style notes</div>
+ <p className="rounded border border-port-border p-2 text-xs text-gray-400 whitespace-pre-wrap">
+ {diff.styleNotes.before || 'None'}
+ </p>
+ </div>
+ <div>
+ <div className="text-[11px] uppercase tracking-wide text-port-accent mb-1">Proposed style notes</div>
+ <p className="rounded border border-port-accent/30 p-2 text-xs text-gray-200 whitespace-pre-wrap">
+ {diff.styleNotes.after || 'Clear style notes'}
+ </p>
+ </div>
+ </div>
+ ) : null}
+ <TokenDiff label="Positive guidance changes" diff={diff.influences?.embrace} tone="positive" />
+ <TokenDiff label="Negative guidance changes" diff={diff.influences?.avoid} tone="negative" />
+ {analysis.rationale ? <p className="text-xs text-gray-400">{analysis.rationale}</p> : null}
+ </section>
+ );
+}
+
+export default function UniverseStyleReferences({
+ universe,
+ saved,
+ onPersist,
+ onRemove,
+}) {
+ const references = Array.isArray(universe?.styleReferences) ? universe.styleReferences : [];
+ const [open, setOpen] = useState(false);
+ const [galleryOpen, setGalleryOpen] = useState(false);
+ const [image, setImage] = useState(null);
+ const [title, setTitle] = useState('');
+ const [prompt, setPrompt] = useState('');
+ const [vision, setVision] = useState({ providerId: '', model: '' });
+ const [analysis, setAnalysis] = useState(null);
+ const [analyzing, setAnalyzing] = useState(false);
+ const [persisting, setPersisting] = useState(false);
+
+ const reset = () => {
+ setImage(null);
+ setTitle('');
+ setPrompt('');
+ setAnalysis(null);
+ setVision({ providerId: '', model: '' });
+ };
+ const close = () => {
+ if (analyzing || persisting) return;
+ setOpen(false);
+ reset();
+ };
+
+ const analyze = async () => {
+ if (!image?.filename || !vision.model) return;
+ setAnalyzing(true);
+ const result = await analyzeUniverseStyleReference({
+ image: image.filename,
+ title: title.trim() || undefined,
+ prompt: prompt.trim() || undefined,
+ styleNotes: universe.styleNotes || '',
+ influences: universe.influences || {},
+ locked: universe.locked || {},
+ providerId: vision.providerId || undefined,
+ model: vision.model,
+ }, { silent: true }).catch((error) => {
+ toast.error(`Style analysis failed: ${error.message}`);
+ return null;
+ });
+ setAnalyzing(false);
+ if (!result) return;
+ setAnalysis(result);
+ setTitle(result.reference?.title || '');
+ setPrompt(result.reference?.prompt || '');
+ };
+
+ const persist = async (adopt) => {
+ if (!analysis || !title.trim() || !prompt.trim()) return;
+ setPersisting(true);
+ const ok = await onPersist?.({
+ ...analysis,
+ reference: { ...analysis.reference, title: title.trim(), prompt: prompt.trim() },
+ adopt,
+ });
+ setPersisting(false);
+ if (ok) {
+ setOpen(false);
+ reset();
+ }
+ };
+
+ return (
+ <section className="mt-4 pt-4 border-t border-port-border space-y-3">
+ <div className="flex items-start justify-between gap-3 flex-wrap">
+ <div>
+ <h3 className="text-sm font-medium text-white">Art style references</h3>
+ <p className="text-xs text-gray-500">
+ Uploaded visual references with vision-authored recreation prompts.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ disabled={!saved || references.length >= WORLD_STYLE_REFERENCES_MAX}
+ title={!saved
+ ? 'Save the universe before adding references'
+ : references.length >= WORLD_STYLE_REFERENCES_MAX
+ ? `A universe can hold up to ${WORLD_STYLE_REFERENCES_MAX} art references`
+ : 'Upload or choose an art style reference'}
+ className="inline-flex min-h-[38px] items-center gap-1.5 rounded border border-port-accent/40 px-2.5 py-1.5 text-xs text-port-accent hover:bg-port-accent/10 disabled:opacity-50"
+ >
+ <ImagePlus size={14} />
+ Add art reference
+ </button>
+ </div>
+
+ {references.length ? (
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
+ {references.map((reference) => {
+ const filename = reference.imageRefs?.[0];
+ return (
+ <article key={reference.id} className="flex gap-3 rounded-lg border border-port-border bg-port-bg/40 p-2">
+ <img
+ src={`/data/images/${encodeURIComponent(filename || '')}`}
+ alt={reference.title}
+ className="h-24 w-24 shrink-0 rounded object-cover bg-port-bg"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-start justify-between gap-2">
+ <h4 className="text-sm font-medium text-white">{reference.title}</h4>
+ <button
+ type="button"
+ onClick={() => onRemove?.(reference.id)}
+ className="shrink-0 rounded p-1 text-gray-500 hover:bg-white/5 hover:text-port-error"
+ aria-label={`Remove ${reference.title}`}
+ title="Remove art reference"
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
+ <p className="mt-1 line-clamp-3 text-xs text-gray-400">{reference.prompt}</p>
+ </div>
+ </article>
+ );
+ })}
+ </div>
+ ) : (
+ <p className="text-xs text-gray-600">No art style references yet.</p>
+ )}
+
+ <Modal
+ open={open}
+ onClose={close}
+ size="2xl"
+ closeOnBackdrop={!analyzing && !persisting}
+ usePortal
+ panelClassName="bg-port-card border border-port-border rounded-xl max-h-[90vh] overflow-y-auto"
+ ariaLabel="Add universe art style reference"
+ >
+ <div className="p-4 space-y-4">
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <h2 className="text-base font-semibold text-white">Add art style reference</h2>
+ <p className="text-xs text-gray-500">Choose an image, analyze it, then preview whether to adopt its style.</p>
+ </div>
+ <button type="button" onClick={close} disabled={analyzing || persisting} className="p-1 text-gray-400 hover:text-white" aria-label="Close">
+ <X size={18} />
+ </button>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4">
+ <div>
+ {image ? (
+ <button type="button" onClick={() => { setImage(null); setAnalysis(null); }} className="block w-full" title="Choose another image">
+ <img src={image.preview || `/data/images/${encodeURIComponent(image.filename)}`} alt="Selected art reference" className="aspect-square w-full rounded-lg border border-port-border object-cover" />
+ </button>
+ ) : (
+ <button type="button" onClick={() => setGalleryOpen(true)} className="flex aspect-square w-full flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-port-border text-xs text-gray-400 hover:border-port-accent hover:text-white">
+ <ImagePlus size={24} />
+ Upload or choose image
+ </button>
+ )}
+ </div>
+ <div className="space-y-3">
+ <div>
+ <label htmlFor="style-reference-title" className="mb-1 block text-xs text-gray-400">Title (optional before analysis)</label>
+ <input id="style-reference-title" value={title} onChange={(event) => setTitle(event.target.value)} maxLength={TITLE_MAX} placeholder="Generated from the image when blank" className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none" />
+ </div>
+ <div>
+ <label htmlFor="style-reference-prompt" className="mb-1 block text-xs text-gray-400">Recreation prompt (optional before analysis)</label>
+ <textarea id="style-reference-prompt" value={prompt} onChange={(event) => setPrompt(event.target.value)} maxLength={PROMPT_MAX} rows={5} placeholder="Generated from the image when blank" className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none" />
+ </div>
+ <VisionProviderPicker label="Vision model for style analysis" onChange={setVision} />
+ </div>
+ </div>
+
+ <StyleDiff analysis={analysis} />
+
+ <div className="flex items-center justify-end gap-2 flex-wrap">
+ <button type="button" onClick={close} disabled={analyzing || persisting} className="min-h-[38px] px-3 text-sm text-gray-400 hover:text-white disabled:opacity-50">Cancel</button>
+ {!analysis ? (
+ <button type="button" onClick={analyze} disabled={analyzing || !image?.filename || !vision.model} className="inline-flex min-h-[38px] items-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50">
+ {analyzing ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {analyzing ? 'Analyzing…' : 'Analyze image'}
+ </button>
+ ) : (
+ <>
+ <button type="button" onClick={() => persist(false)} disabled={persisting || !title.trim() || !prompt.trim()} className="min-h-[38px] rounded border border-port-border px-3 py-2 text-sm text-gray-200 hover:bg-white/5 disabled:opacity-50">
+ Add reference only
+ </button>
+ <button type="button" onClick={() => persist(true)} disabled={persisting || !title.trim() || !prompt.trim()} className="inline-flex min-h-[38px] items-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50">
+ {persisting ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ Adopt style + add
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ </Modal>
+ <GalleryImagePicker
+ open={galleryOpen}
+ onClose={() => setGalleryOpen(false)}
+ allowUpload
+ onSelect={(item) => {
+ if (!item?.filename) return;
+ setImage({ filename: item.filename, preview: item.previewUrl });
+ setAnalysis(null);
+ }}
+ />
+ </section>
+ );
+}
diff --git a/client/src/components/universeBuilder/UniverseStyleReferences.test.jsx b/client/src/components/universeBuilder/UniverseStyleReferences.test.jsx
new file mode 100644
index 0000000000..ce4e901388
--- /dev/null
+++ b/client/src/components/universeBuilder/UniverseStyleReferences.test.jsx
@@ -0,0 +1,95 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import UniverseStyleReferences from './UniverseStyleReferences';
+
+const apiMocks = vi.hoisted(() => ({
+ analyzeUniverseStyleReference: vi.fn(),
+}));
+vi.mock('../../services/api', () => ({
+ ...apiMocks,
+ WORLD_STYLE_REFERENCES_MAX: 20,
+}));
+vi.mock('../imageGen/GalleryImagePicker', () => ({
+ default: ({ open, onSelect }) => open
+ ? <button onClick={() => onSelect({ filename: 'reference.png', previewUrl: 'data:image/png;base64,x' })}>Select gallery image</button>
+ : null,
+}));
+vi.mock('../universe/VisionProviderPicker', () => ({
+ default: ({ onChange }) => (
+ <button onClick={() => onChange({ providerId: 'ollama', model: 'qwen-vl' })}>Select vision model</button>
+ ),
+}));
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
+const universe = {
+ id: 'u1',
+ styleNotes: 'Clean vector art',
+ influences: { embrace: ['clean vectors'], avoid: ['grain'] },
+ locked: {},
+ styleReferences: [],
+};
+const analysis = {
+ reference: {
+ id: 'style-ref-1',
+ title: 'Dust-lit ink wash',
+ prompt: 'Granular ink wash with muted ochre.',
+ imageRefs: ['reference.png'],
+ },
+ proposed: {
+ styleNotes: 'Tactile ink-wash science fiction.',
+ influences: { embrace: ['ink wash'], avoid: ['gloss'] },
+ },
+ diff: {
+ hasChanges: true,
+ styleNotes: { before: 'Clean vector art', after: 'Tactile ink-wash science fiction.', changed: true },
+ influences: {
+ embrace: { changed: true, added: ['ink wash'], removed: ['clean vectors'] },
+ avoid: { changed: true, added: ['gloss'], removed: ['grain'] },
+ },
+ },
+ rationale: 'The reference favors tactile marks.',
+};
+
+describe('UniverseStyleReferences', () => {
+ it('analyzes an uploaded/gallery image, previews the diff, and adopts on explicit confirmation', async () => {
+ apiMocks.analyzeUniverseStyleReference.mockResolvedValue(analysis);
+ const onPersist = vi.fn().mockResolvedValue(true);
+ render(<UniverseStyleReferences universe={universe} saved onPersist={onPersist} onRemove={() => {}} />);
+
+ fireEvent.click(screen.getByRole('button', { name: /Add art reference/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Upload or choose image/i }));
+ fireEvent.click(screen.getByRole('button', { name: 'Select gallery image' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Select vision model' }));
+ fireEvent.click(screen.getByRole('button', { name: /Analyze image/i }));
+
+ expect(await screen.findByText('Style guide preview')).toBeInTheDocument();
+ expect(screen.getByText('+ ink wash')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /Adopt style \+ add/i }));
+
+ await waitFor(() => expect(onPersist).toHaveBeenCalledWith(
+ expect.objectContaining({
+ adopt: true,
+ reference: expect.objectContaining({ title: 'Dust-lit ink wash' }),
+ }),
+ ));
+ await waitFor(() => expect(
+ screen.queryByRole('heading', { name: 'Add art style reference' }),
+ ).not.toBeInTheDocument());
+ });
+
+ it('can add the analyzed reference without adopting the proposed style', async () => {
+ apiMocks.analyzeUniverseStyleReference.mockResolvedValue(analysis);
+ const onPersist = vi.fn().mockResolvedValue(true);
+ render(<UniverseStyleReferences universe={universe} saved onPersist={onPersist} onRemove={() => {}} />);
+ fireEvent.click(screen.getByRole('button', { name: /Add art reference/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Upload or choose image/i }));
+ fireEvent.click(screen.getByRole('button', { name: 'Select gallery image' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Select vision model' }));
+ fireEvent.click(screen.getByRole('button', { name: /Analyze image/i }));
+ await screen.findByText('Style guide preview');
+ fireEvent.click(screen.getByRole('button', { name: /Add reference only/i }));
+ await waitFor(() => expect(onPersist).toHaveBeenCalledWith(
+ expect.objectContaining({ adopt: false }),
+ ));
+ });
+});
diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.js
index ffcc1dc761..88c25ad34d 100644
--- a/client/src/hooks/useUniverseDraft.js
+++ b/client/src/hooks/useUniverseDraft.js
@@ -12,6 +12,7 @@ import {
listWorldRuns,
updateUniverse,
WORLD_LOCKABLE_FIELDS,
+ WORLD_STYLE_REFERENCES_MAX,
ensureInfluences,
} from '../services/api';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
@@ -35,12 +36,14 @@ export const createEmptyUniverseDraft = () => ({
categories: ensureDraftCategories(),
compositeSheets: [],
influences: { embrace: [], avoid: [] },
+ styleReferences: [],
locked: {},
llm: { provider: null, model: null },
});
-// Stable serialization of the fields the general Save action owns. Canon is
-// excluded because its targeted editors persist those arrays independently.
+// Stable serialization of the fields the general Save action owns. Canon and
+// styleReferences are excluded because targeted editors persist those
+// arrays independently.
export const universeDraftSnapshot = (draft = {}) => JSON.stringify({
name: (draft.name || '').trim(),
starterPrompt: draft.starterPrompt || '',
@@ -100,6 +103,17 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
savedStyleSnapshotRef.current = ensureInfluences(snapshotSource?.influences);
}, []);
+ // Mark only the style-guide fields as saved after an atomic reference-adopt
+ // PATCH. Replacing the entire baseline here would incorrectly clear dirty
+ // state for unrelated edits made while the vision request was in flight.
+ const markStyleGuidanceSaved = useCallback((snapshotSource) => {
+ const saved = JSON.parse(savedDraftSnapshotRef.current);
+ saved.styleNotes = snapshotSource?.styleNotes || '';
+ saved.influences = ensureInfluences(snapshotSource?.influences);
+ savedDraftSnapshotRef.current = JSON.stringify(saved);
+ savedStyleSnapshotRef.current = ensureInfluences(snapshotSource?.influences);
+ }, []);
+
const isDraftDirty = useCallback(
() => savedDraftSnapshotRef.current !== universeDraftSnapshot(draftRef.current || draft),
[draft],
@@ -155,6 +169,7 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
premise: universe.premise || '',
styleNotes: universe.styleNotes || '',
influences: ensureInfluences(universe.influences),
+ styleReferences: universe.styleReferences || [],
locked: universe.locked || {},
llm: universe.llm || { provider: null, model: null },
};
@@ -261,6 +276,71 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
const updateDraft = useCallback((patch) => setDraft((current) => ({ ...current, ...patch })), []);
+ const persistStyleReference = useCallback(async ({ reference, proposed, adopt }) => {
+ if (!selectedId || !reference) return false;
+ const current = draftRef.current || draft;
+ const capturedStyle = {
+ styleNotes: current.styleNotes || '',
+ influences: ensureInfluences(current.influences),
+ };
+ if ((current.styleReferences || []).length >= WORLD_STYLE_REFERENCES_MAX) {
+ toast.error(`A universe can hold up to ${WORLD_STYLE_REFERENCES_MAX} art references`);
+ return false;
+ }
+ const styleReferences = [
+ ...(Array.isArray(current.styleReferences) ? current.styleReferences : []),
+ reference,
+ ];
+ const patch = {
+ styleReferences,
+ ...(adopt ? {
+ styleNotes: proposed?.styleNotes || '',
+ influences: ensureInfluences(proposed?.influences),
+ } : {}),
+ };
+ const updated = await updateUniverse(selectedId, patch, { silent: true }).catch((error) => {
+ toast.error(`Reference save failed: ${error.message}`);
+ return null;
+ });
+ if (!updated) return false;
+ if (adopt) markStyleGuidanceSaved(updated);
+ setDraft((latest) => {
+ const styleUnchangedDuringSave = latest.styleNotes === capturedStyle.styleNotes
+ && sameJsonShape(ensureInfluences(latest.influences), capturedStyle.influences);
+ return {
+ ...latest,
+ styleReferences: updated.styleReferences || [],
+ updatedAt: updated.updatedAt,
+ ...(adopt && styleUnchangedDuringSave ? {
+ styleNotes: updated.styleNotes || '',
+ influences: ensureInfluences(updated.influences),
+ } : {}),
+ };
+ });
+ setWorlds((previous) => upsertByIdPrepend(previous, updated));
+ toast.success(adopt ? 'Art reference added and style guide updated' : 'Art reference added');
+ return true;
+ }, [draft, markStyleGuidanceSaved, selectedId]);
+
+ const removeStyleReference = useCallback(async (referenceId) => {
+ if (!selectedId) return false;
+ const current = draftRef.current || draft;
+ const styleReferences = (current.styleReferences || []).filter((item) => item.id !== referenceId);
+ const updated = await updateUniverse(selectedId, { styleReferences }, { silent: true }).catch((error) => {
+ toast.error(`Reference removal failed: ${error.message}`);
+ return null;
+ });
+ if (!updated) return false;
+ setDraft((latest) => ({
+ ...latest,
+ styleReferences: updated.styleReferences || [],
+ updatedAt: updated.updatedAt,
+ }));
+ setWorlds((previous) => upsertByIdPrepend(previous, updated));
+ toast.success('Art reference removed');
+ return true;
+ }, [draft, selectedId]);
+
const handleCanonChange = useCallback((updated) => {
if (!updated) return;
setDraft((current) => {
@@ -404,7 +484,9 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
providerLabel,
providerModels,
providers,
+ persistStyleReference,
removeCategory,
+ removeStyleReference,
runs,
saving,
setCanonDirty,
diff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsx
index f6a7c3fe5f..b98d87e743 100644
--- a/client/src/hooks/useUniverseDraft.test.jsx
+++ b/client/src/hooks/useUniverseDraft.test.jsx
@@ -15,6 +15,7 @@ const apiMocks = vi.hoisted(() => ({
WORLD_CATEGORY_KEY_MAX: 64,
WORLD_CATEGORIES: ['characters', 'places', 'objects'],
WORLD_LOCKABLE_FIELDS: ['starterPrompt', 'logline', 'premise', 'styleNotes'],
+ WORLD_STYLE_REFERENCES_MAX: 20,
ensureInfluences: (value) => ({
embrace: Array.isArray(value?.embrace) ? value.embrace : [],
avoid: Array.isArray(value?.avoid) ? value.avoid : [],
@@ -37,6 +38,7 @@ const universe = {
categories: { heroes: { kind: 'characters', variations: [] } },
compositeSheets: [],
influences: { embrace: ['ink'], avoid: [] },
+ styleReferences: [],
locked: {},
llm: { provider: null, model: null },
characters: [{ name: 'Stale Draft Character' }],
@@ -108,4 +110,56 @@ describe('useUniverseDraft', () => {
]);
expect(payload.characters).not.toContainEqual({ name: 'Stale Draft Character' });
});
+
+ it('atomically adds a reference and adopted guidance without clearing unrelated dirty edits', async () => {
+ const { result } = renderDraft();
+ await waitFor(() => expect(result.current.draft.id).toBe('u1'));
+ act(() => result.current.updateDraft({ premise: 'Unsaved concurrent premise' }));
+
+ const reference = {
+ id: 'style-ref-1',
+ title: 'Ink wash',
+ prompt: 'Granular ink wash',
+ imageRefs: ['reference.png'],
+ };
+ await act(async () => {
+ await result.current.persistStyleReference({
+ reference,
+ proposed: {
+ styleNotes: 'Tactile and muted',
+ influences: { embrace: ['ink wash'], avoid: ['gloss'] },
+ },
+ adopt: true,
+ });
+ });
+
+ const payload = apiMocks.updateUniverse.mock.calls.at(-1)[1];
+ expect(payload).toEqual({
+ styleReferences: [reference],
+ styleNotes: 'Tactile and muted',
+ influences: { embrace: ['ink wash'], avoid: ['gloss'] },
+ });
+ expect(result.current.draft).toMatchObject({
+ premise: 'Unsaved concurrent premise',
+ styleNotes: 'Tactile and muted',
+ styleReferences: [reference],
+ });
+ expect(result.current.isDraftDirty()).toBe(true);
+ });
+
+ it('removes one style reference through its targeted patch', async () => {
+ const reference = {
+ id: 'style-ref-1',
+ title: 'Ink wash',
+ prompt: 'Granular ink wash',
+ imageRefs: ['reference.png'],
+ };
+ apiMocks.getUniverse.mockResolvedValueOnce({ ...universe, styleReferences: [reference] });
+ const { result } = renderDraft();
+ await waitFor(() => expect(result.current.draft.styleReferences).toEqual([reference]));
+
+ await act(async () => { await result.current.removeStyleReference(reference.id); });
+ expect(apiMocks.updateUniverse.mock.calls.at(-1)[1]).toEqual({ styleReferences: [] });
+ expect(result.current.draft.styleReferences).toEqual([]);
+ });
});
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index b0a7a84541..1d2cb32b2d 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -13,6 +13,7 @@ export const WORLD_STYLE_NOTES_MAX = 4000;
// enforcement and to bound paste-floods of refs.
export const WORLD_INFLUENCE_ENTRY_MAX = 120;
export const WORLD_INFLUENCES_PER_LIST_MAX = 30;
+export const WORLD_STYLE_REFERENCES_MAX = 20;
// `options` lets a caller that owns its own error toast pass `{ silent: true }`
// so request() doesn't also toast — see CLAUDE.md "Custom catch ⇒ silent: true".
@@ -71,6 +72,19 @@ export const describeEntityFromImages = ({
...options,
});
+// Analyze one peer-syncable gallery image as a universe-bible art reference.
+// Returns a proposed reference plus a before/after style-guidance diff; this
+// endpoint is review-only and does not mutate the universe.
+export const analyzeUniverseStyleReference = ({
+ image, title, prompt, styleNotes, influences, locked, providerId, model,
+} = {}, options = {}) => request('/universe-builder/analyze-style-reference', {
+ method: 'POST',
+ body: JSON.stringify({
+ image, title, prompt, styleNotes, influences, locked, providerId, model,
+ }),
+ ...options,
+});
+
// Vision-driven structured expand (characters only): a vision model reads
// reference image(s) and PROPOSES values for the character's still-blank
// structured fields. Review-only — resolves to `{ fields, updatedFields, llm }`
diff --git a/scripts/migrations/207-universe-style-references.js b/scripts/migrations/207-universe-style-references.js
new file mode 100644
index 0000000000..899c7efdcb
--- /dev/null
+++ b/scripts/migrations/207-universe-style-references.js
@@ -0,0 +1,10 @@
+/**
+ * Register universe style-reference schema v5.
+ *
+ * Universe records live as JSONB and are sanitized lazily, so no DDL is
+ * required. Existing rows read with `styleReferences: []`; their next normal
+ * write persists the v5 shape. Federation gates the wire field separately.
+ */
+export async function up() {
+ console.log('✅ Universe style-reference schema registered (lazy JSONB backfill)');
+}
diff --git a/scripts/migrations/207-universe-style-references.test.js b/scripts/migrations/207-universe-style-references.test.js
new file mode 100644
index 0000000000..3b5e067d42
--- /dev/null
+++ b/scripts/migrations/207-universe-style-references.test.js
@@ -0,0 +1,11 @@
+import { describe, expect, it, vi } from 'vitest';
+import { up } from './207-universe-style-references.js';
+
+describe('migration 207 — universe style references', () => {
+ it('registers the lazy JSONB migration without touching user data', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ await expect(up()).resolves.toBeUndefined();
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('lazy JSONB backfill'));
+ log.mockRestore();
+ });
+});
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 8d7d426498..572b57d14e 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -33,8 +33,8 @@ import { PATHS, tryReadFile, safeJSONParse } from './fileUtils.js';
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`).
+ // v5 = post-split. Migration 034 introduced it. The independent per-record
+ // shape is currently v5 (stamped inside each record by `sanitizeTemplate`).
// 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
@@ -60,7 +60,9 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// sync with version-mismatched peers for one additive field, the heavier
// tradeoff this project has chosen against for additive bible fields. The
// `universes` gate above already protects the canonical (embedded) copy.
- universes: 7,
+ // v8 adds shared styleReferences[]. Older peers must not sanitize the field
+ // away and LWW-sync that loss back to a newer install.
+ universes: 8,
// 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 7c5a8dc651..b4f3a4d728 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -19,9 +19,9 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
// must ship alongside it. The test exists to make a layout bump a
// deliberate two-file edit.
// v6 = canon characters gained relationshipLinks[] (#1287); v7 = canon
- // objects gained attachments[] (#1288). Both additive + version-gated so an
- // older peer can't strip-then-LWW the field back.
- expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(7);
+ // objects gained attachments[] (#1288); v8 adds styleReferences[]. These
+ // are additive + version-gated so an older peer cannot strip-then-LWW them.
+ expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(8);
});
it('declares pipeline collection layout versions', () => {
@@ -45,14 +45,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(7);
+ expect(meta.schemaVersions.universes).toBe(8);
expect(meta.schemaVersions.pipelineIssues).toBe(2);
expect(meta.schemaVersions.pipelineSeries).toBe(12);
});
it('overrides merge into schemaVersions', async () => {
const meta = await buildPortosMeta({ schemaVersions: { future: 1 } });
- expect(meta.schemaVersions.universes).toBe(7);
+ expect(meta.schemaVersions.universes).toBe(8);
expect(meta.schemaVersions.future).toBe(1);
});
});
@@ -200,7 +200,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: 7, pipelineSeries: 2, pipelineIssues: 2, mediaCollections: 2 },
+ { universes: 8, pipelineSeries: 2, pipelineIssues: 2, mediaCollections: 2 },
PORTOS_SCHEMA_VERSIONS,
);
expect(union.compatible).toBe(false); // mediaCollections 2 > 1
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 1d60d7f6c6..e250fb46b1 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -8,6 +8,7 @@
* DELETE /api/universe-builder/:id → { id }
* POST /api/universe-builder/expand → { logline, premise, styleNotes, influences, categories, compositeSheets, characters, places, objects, llm }
* POST /api/universe-builder/describe-from-images → { description, llm }
+ * POST /api/universe-builder/analyze-style-reference → { reference, proposed, diff, rationale, llm }
* POST /api/universe-builder/:id/characters/:entryId/expand-from-images → { fields, updatedFields, llm }
* POST /api/universe-builder/:id/render → { runId, collectionId, jobIds, promptCount }
* GET /api/universe-builder/:id/runs → Run[]
@@ -30,6 +31,7 @@ import { getUniverseCanonUsage, listLinkedSeriesNames } from '../services/canonU
import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';
import { describeEntityFromImages, VISION_KINDS, VISION_MAX_IMAGES } from '../services/universeVisionDescribe.js';
import { expandEntityFromImages, VISION_EXPAND_MAX_IMAGES } from '../services/universeVisionExpand.js';
+import { analyzeUniverseStyleReference } from '../services/universeStyleReference.js';
import { sanitizeFilename, PATHS, resolveGalleryImage } from '../lib/fileUtils.js';
import { existsSync } from 'fs';
import { join } from 'path';
@@ -125,6 +127,14 @@ const influencesSchema = z.object({
embrace: z.array(influenceEntrySchema).max(svc.INFLUENCES_PER_LIST_MAX).optional().default([]),
avoid: z.array(influenceEntrySchema).max(svc.INFLUENCES_PER_LIST_MAX).optional().default([]),
}).strict();
+const styleReferenceSchema = z.object({
+ id: entryIdField,
+ title: z.string().trim().min(1).max(svc.STYLE_REFERENCE_TITLE_MAX),
+ prompt: z.string().trim().min(1).max(svc.STYLE_REFERENCE_PROMPT_MAX),
+ imageRefs: z.array(entryImageRefField).min(1).max(1),
+ createdAt: z.string().trim().min(1).max(64).optional(),
+}).strict();
+const styleReferencesField = z.array(styleReferenceSchema).max(svc.STYLE_REFERENCES_MAX).optional();
// Legacy prose prompts: the v2 universe template carried `stylePrompt` /
// `negativePrompt` as comma-separated prose strings; v3 collapses them into
@@ -155,6 +165,7 @@ const createSchema = z.object({
categories: categoriesSchema.optional(),
compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
influences: influencesSchema.optional(),
+ styleReferences: styleReferencesField,
// Base "style probe" render filenames — sanitized + capped server-side.
// Match the sanitizer cap so over-the-cap requests get a loud 400 instead
// of a silent 200 with N entries dropped (sanitizer keeps the most recent
@@ -188,6 +199,7 @@ const patchSchema = z.object({
categories: categoriesSchema.optional(),
compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
influences: influencesSchema.optional(),
+ styleReferences: styleReferencesField,
// Base "style probe" render filenames — sanitized + capped server-side.
// Match the sanitizer cap so over-the-cap requests get a loud 400 instead
// of a silent 200 with N entries dropped (sanitizer keeps the most recent
@@ -469,6 +481,43 @@ router.post('/describe-from-images', asyncHandler(async (req, res) => {
res.json(result);
}));
+const analyzeStyleReferenceSchema = z.object({
+ image: z.string().trim().min(1).max(300),
+ title: z.string().trim().max(svc.STYLE_REFERENCE_TITLE_MAX).optional(),
+ prompt: z.string().trim().max(svc.STYLE_REFERENCE_PROMPT_MAX).optional(),
+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),
+ influences: influencesSchema.optional().default({ embrace: [], avoid: [] }),
+ locked: lockedSchema.optional().default({}),
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+});
+
+// Stateless review step: analyze the image and return a proposed record plus a
+// diff. Persistence only happens after the user chooses reference-only or
+// reference-and-adopt in the client.
+router.post('/analyze-style-reference', asyncHandler(async (req, res) => {
+ const body = validateRequest(analyzeStyleReferenceSchema, req.body ?? {});
+ const imageFilename = sanitizeFilename(body.image);
+ if (imageFilename !== body.image) {
+ throw new ServerError(`Invalid gallery image filename: ${body.image}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+ const imagePath = resolveGalleryImage(imageFilename);
+ if (!imagePath) {
+ throw new ServerError(`Gallery image not found: ${imageFilename} — upload it again and retry.`, {
+ status: 400,
+ code: 'GALLERY_IMAGE_NOT_FOUND',
+ });
+ }
+ res.json(await analyzeUniverseStyleReference({
+ ...body,
+ imagePath,
+ imageFilename,
+ }));
+}));
+
// Refines the 3 top-level prompts (starter / style / negative) based on
// user feedback. Stateless — the caller decides whether to write the
// result back to a saved universe. Keep ahead of `/:id`.
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index e496346759..d59e5d8c06 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -51,6 +51,22 @@ const refineWorldPromptsMock = vi.fn(async (args) => ({
vi.mock('../services/universeBuilderRefine.js', () => ({
refineWorldPrompts: (...args) => refineWorldPromptsMock(...args),
}));
+const analyzeUniverseStyleReferenceMock = vi.fn(async (args) => ({
+ reference: {
+ id: 'style-ref-test',
+ title: args.title || 'Analyzed style',
+ prompt: args.prompt || 'Analyzed recreation prompt',
+ imageRefs: [args.imageFilename],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ },
+ proposed: { styleNotes: 'proposed', influences: { embrace: ['ink'], avoid: ['gloss'] } },
+ diff: { hasChanges: true },
+ rationale: 'mock rationale',
+ llm: { provider: 'mock', model: null },
+}));
+vi.mock('../services/universeStyleReference.js', () => ({
+ analyzeUniverseStyleReference: (...args) => analyzeUniverseStyleReferenceMock(...args),
+}));
// Both mocks needed: vitest.setup.js's global `instances.js` mock uses importOriginal, which leaves the per-file `peerSync.js` mock unable to suppress the createUniverse dynamic-import hoist error alone.
vi.mock('../services/instances.js', () => mockNoPeers());
@@ -1123,6 +1139,49 @@ describe('universe-builder routes', () => {
});
});
+ describe('POST /analyze-style-reference', () => {
+ it('resolves the gallery image and forwards supplied metadata and guidance', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/analyze-style-reference')
+ .send({
+ image: 'g.png',
+ title: 'Supplied title',
+ prompt: 'Supplied prompt',
+ styleNotes: 'Current notes',
+ influences: { embrace: ['ink'], avoid: ['gloss'] },
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.reference.title).toBe('Supplied title');
+ expect(analyzeUniverseStyleReferenceMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ imagePath: '/mock/data/images/g.png',
+ imageFilename: 'g.png',
+ styleNotes: 'Current notes',
+ }),
+ );
+ });
+
+ it('rejects a missing gallery image before invoking vision', async () => {
+ analyzeUniverseStyleReferenceMock.mockClear();
+ const res = await request(buildApp())
+ .post('/api/universe-builder/analyze-style-reference')
+ .send({ image: 'missing.png' });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('GALLERY_IMAGE_NOT_FOUND');
+ expect(analyzeUniverseStyleReferenceMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects path-bearing image names instead of silently normalizing them', async () => {
+ analyzeUniverseStyleReferenceMock.mockClear();
+ const res = await request(buildApp())
+ .post('/api/universe-builder/analyze-style-reference')
+ .send({ image: '../g.png' });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(analyzeUniverseStyleReferenceMock).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /:id/characters/:entryId/expand-from-images', () => {
it('resolves mixed sources and forwards universeId/entryId', async () => {
const res = await request(buildApp())
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 17dc561abe..dea163adb3 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(7);
+ expect(snap.portosMeta.schemaVersions.universes).toBe(8);
});
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: 8 } } });
+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 9 } } });
expect(result.applied).toBe(false);
expect(result.count).toBe(0);
expect(result.blockedBySchema).toBeDefined();
expect(result.blockedBySchema.ahead).toEqual([
- { category: 'universes', senderV: 8, receiverV: 7 },
+ { category: 'universes', senderV: 9, receiverV: 8 },
]);
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 415c44fd3d..3931f3aa95 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2312,7 +2312,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(7);
+ expect(manifest.portosSchemaVersions.universes).toBe(8);
});
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 e63ccd4768..f05dae9782 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3490,17 +3490,17 @@ describe('peerSync', () => {
describe('receiver — applyIncomingPush', () => {
it('rejects when sender schemaVersions.universes is AHEAD of local code', async () => {
- // Local code is at universes:7 (see server/lib/schemaVersions.js).
- // A push from a sender on universes:8 must NOT touch local state.
+ // Local code is at universes:8 (see server/lib/schemaVersions.js).
+ // A push from a sender on universes:9 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: 8 } },
+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 9 } },
}).catch((err) => err);
expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');
- expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 8, receiverV: 7 }]);
+ expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 9, receiverV: 8 }]);
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
@@ -3741,7 +3741,7 @@ describe('peerSync', () => {
expect(call).toBeDefined();
const body = JSON.parse(call[1].body);
expect(body.portosMeta).toBeDefined();
- expect(body.portosMeta.schemaVersions.universes).toBe(7);
+ expect(body.portosMeta.schemaVersions.universes).toBe(8);
expect(typeof body.portosMeta.portosVersion).toBe('string');
});
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 678088700d..7df441ed42 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -346,6 +346,38 @@ describe("universeBuilder service", () => {
expect(w.styleImageRefs).toEqual([]);
});
+ it("persists analyzed style references and patches the list wholesale", async () => {
+ const reference = {
+ id: "style-ref-example",
+ title: "Dust-lit ink wash",
+ prompt: "Granular ink wash, muted ochre, weathered silhouettes",
+ imageRefs: ["reference.png"],
+ createdAt: "2026-01-01T00:00:00.000Z",
+ };
+ const w = await svc.createUniverse({
+ name: "Reference Bible",
+ styleReferences: [reference, { ...reference, id: "style-ref-duplicate" }],
+ });
+ expect(w.styleReferences).toHaveLength(2);
+ expect(w.styleReferences[0]).toEqual(reference);
+
+ const patched = await svc.updateUniverse(w.id, { styleReferences: [reference] });
+ expect(patched.styleReferences).toEqual([reference]);
+ expect((await svc.getUniverse(w.id)).styleReferences).toEqual([reference]);
+ });
+
+ it("drops invalid style references and defaults the field to an empty list", async () => {
+ const w = await svc.createUniverse({
+ name: "Reference Validation",
+ styleReferences: [
+ { title: "Missing prompt", imageRefs: ["reference.png"] },
+ { title: "Missing image", prompt: "Prompt", imageRefs: [] },
+ { title: "Traversal", prompt: "Prompt", imageRefs: ["../secret.png"] },
+ ],
+ });
+ expect(w.styleReferences).toEqual([]);
+ });
+
it("createUniverse trims bible fields to their max length", async () => {
const w = await seedWorld({
logline: "x".repeat(svc.LOGLINE_MAX + 50),
@@ -1882,6 +1914,23 @@ describe("universeBuilder service", () => {
});
describe("categories→canon backfill", () => {
+ it("upgrades v4 to v5 without re-folding exploratory categories into canon", () => {
+ const w = svc.sanitizeTemplate({
+ id: "world-v4",
+ name: "Already backfilled",
+ schemaVersion: 4,
+ categories: {
+ landscapes: { kind: "places", variations: [{ label: "New Vista", prompt: "exploratory" }] },
+ },
+ characters: [],
+ places: [],
+ objects: [],
+ });
+ expect(w.schemaVersion).toBe(svc.CURRENT_SCHEMA_VERSION);
+ expect(w.places).toEqual([]);
+ expect(w.styleReferences).toEqual([]);
+ });
+
it("backfills canon arrays from categories on first read + stamps the current schema version", async () => {
await seedState({
universes: [
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index ae0773d477..12a797de7f 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -148,6 +148,7 @@ export async function createUniverse(input = {}) {
categories: input.categories || {},
compositeSheets: input.compositeSheets || [],
influences: input.influences || {},
+ styleReferences: input.styleReferences || [],
styleImageRefs: input.styleImageRefs || [],
locked: input.locked || {},
// Canon registries — let callers seed a universe at creation time
@@ -363,6 +364,8 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
const PATCHABLE_SCALARS = [
'name', 'starterPrompt',
'logline', 'premise', 'styleNotes', 'compositeSheets',
+ // Uploaded, analyzed bible references — patched wholesale.
+ 'styleReferences',
// Base style-probe render refs — patched wholesale (sanitizer re-caps).
'styleImageRefs',
// Canon entity arrays — patched wholesale (the sanitizer reruns
diff --git a/server/services/universeBuilder/db.js b/server/services/universeBuilder/db.js
index bb0f023500..2d13147447 100644
--- a/server/services/universeBuilder/db.js
+++ b/server/services/universeBuilder/db.js
@@ -102,7 +102,7 @@ export async function countUniverses({ includeDeleted = false } = {}) {
export async function writeRaw(id, record) {
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(record?.createdAt, now);
- const schemaVersion = Number.isInteger(record?.schemaVersion) ? record.schemaVersion : 4;
+ const schemaVersion = Number.isInteger(record?.schemaVersion) ? record.schemaVersion : 5;
await query(
`INSERT INTO universes (id, name, data, schema_version, ephemeral, created_at, updated_at, deleted, deleted_at)
VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7, $8, $9)
diff --git a/server/services/universeBuilder/sanitize.js b/server/services/universeBuilder/sanitize.js
index 986bf7ba14..d8d97bc264 100644
--- a/server/services/universeBuilder/sanitize.js
+++ b/server/services/universeBuilder/sanitize.js
@@ -29,7 +29,10 @@ import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
// trunks (characters/places/objects/other); the default `characters`
// category is retired and any variations get folded into canon
// characters[]. See "Categories vs canon — decision" in PLAN.md.
-export const CURRENT_SCHEMA_VERSION = 4;
+// v5 — styleReferences stores uploaded visual references with their
+// vision-authored title and recreation prompt.
+export const CURRENT_SCHEMA_VERSION = 5;
+const CANON_CATEGORY_SCHEMA_VERSION = 4;
export const ERR_NOT_FOUND = 'NOT_FOUND';
export const ERR_VALIDATION = 'VALIDATION_ERROR';
@@ -87,6 +90,9 @@ export const ENTRY_REF_KIND = Object.freeze({
// per-variation prompt at render-compile time.
export const INFLUENCE_ENTRY_MAX = 120;
export const INFLUENCES_PER_LIST_MAX = 30;
+export const STYLE_REFERENCE_TITLE_MAX = 120;
+export const STYLE_REFERENCE_PROMPT_MAX = 4000;
+export const STYLE_REFERENCES_MAX = 20;
// Top-level fields the user can lock against AI-driven changes (refine /
// expand). When a field is locked, both the refiner and the expansion-merge
@@ -249,6 +255,35 @@ const sanitizeEntryImageRefs = (raw) => {
: out;
};
+export const sanitizeStyleReference = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const title = trimTo(raw.title, STYLE_REFERENCE_TITLE_MAX);
+ const prompt = trimTo(raw.prompt, STYLE_REFERENCE_PROMPT_MAX);
+ const imageRefs = sanitizeEntryImageRefs(raw.imageRefs).slice(-1);
+ if (!title || !prompt || imageRefs.length === 0) return null;
+ return {
+ id: ensureEntryId(raw.id, 'style-ref-'),
+ title,
+ prompt,
+ imageRefs,
+ createdAt: isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString(),
+ };
+};
+
+export const sanitizeStyleReferences = (raw) => {
+ if (!Array.isArray(raw)) return [];
+ const out = [];
+ const seen = new Set();
+ for (const candidate of raw) {
+ const reference = sanitizeStyleReference(candidate);
+ if (!reference || seen.has(reference.id)) continue;
+ seen.add(reference.id);
+ out.push(reference);
+ if (out.length >= STYLE_REFERENCES_MAX) break;
+ }
+ return out;
+};
+
const sanitizeVariation = (raw) => {
if (!raw || typeof raw !== 'object') return null;
const label = trimTo(raw.label, VARIATION_LABEL_MAX);
@@ -581,12 +616,12 @@ function foldRetiredCharactersBucket(raw, canon) {
function backfillCanonFromCategories(raw, existingCanon) {
// v4 hot path — already backfilled. Sanitize through the kind sanitizers
// once and return; no category scan needed.
- if (raw.schemaVersion >= CURRENT_SCHEMA_VERSION) {
+ if (raw.schemaVersion >= CANON_CATEGORY_SCHEMA_VERSION) {
return {
characters: sanitizeBibleList(existingCanon.characters, BIBLE_KIND.CHARACTER),
places: sanitizeBibleList(existingCanon.places, BIBLE_KIND.PLACE),
objects: sanitizeBibleList(existingCanon.objects, BIBLE_KIND.OBJECT),
- schemaVersion: raw.schemaVersion,
+ schemaVersion: CURRENT_SCHEMA_VERSION,
};
}
@@ -709,6 +744,10 @@ export const sanitizeTemplate = (raw) => {
categories,
compositeSheets,
influences,
+ // Shared, user-selected visual references. Their nested imageRefs are
+ // discovered by federation/export asset collection so the image bytes
+ // travel with the universe.
+ styleReferences: sanitizeStyleReferences(raw.styleReferences),
// Base "style probe" renders — images generated from the raw style preset
// (influences embrace/avoid + styleNotes) with NO subject, so the user can
// see the world's base visual emphasis. Additive + regenerable; sanitized
diff --git a/server/services/universeStyleReference.js b/server/services/universeStyleReference.js
new file mode 100644
index 0000000000..1b92384e8f
--- /dev/null
+++ b/server/services/universeStyleReference.js
@@ -0,0 +1,173 @@
+/**
+ * Stateless vision analysis for a universe-bible art-style reference.
+ *
+ * The service proposes both a reference record and style-guide changes. The
+ * client later chooses whether to persist only the reference or atomically
+ * persist it together with the proposed guidance.
+ */
+
+import { randomUUID } from 'crypto';
+import { parseLLMJSON, resolveAPIProvider } from '../lib/aiProvider.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { assertProvider, assertVisionRunUsedImages, runPromptThroughProvider } from '../lib/promptRunner.js';
+import { trimTo } from '../lib/storyBible.js';
+import {
+ sanitizeInfluences,
+ sanitizeLocked,
+ STYLE_NOTES_MAX,
+ STYLE_REFERENCE_PROMPT_MAX,
+ STYLE_REFERENCE_TITLE_MAX,
+} from './universeBuilder.js';
+
+const listDiff = (before, after) => {
+ const beforeKeys = new Set(before.map((value) => value.toLowerCase()));
+ const afterKeys = new Set(after.map((value) => value.toLowerCase()));
+ return {
+ before,
+ after,
+ added: after.filter((value) => !beforeKeys.has(value.toLowerCase())),
+ removed: before.filter((value) => !afterKeys.has(value.toLowerCase())),
+ changed: JSON.stringify(before) !== JSON.stringify(after),
+ };
+};
+
+export function buildStyleReferenceDiff(current, proposed) {
+ const beforeInfluences = sanitizeInfluences(current?.influences);
+ const afterInfluences = sanitizeInfluences(proposed?.influences);
+ const styleNotes = {
+ before: trimTo(current?.styleNotes, STYLE_NOTES_MAX),
+ after: trimTo(proposed?.styleNotes, STYLE_NOTES_MAX),
+ };
+ styleNotes.changed = styleNotes.before !== styleNotes.after;
+ const embrace = listDiff(beforeInfluences.embrace, afterInfluences.embrace);
+ const avoid = listDiff(beforeInfluences.avoid, afterInfluences.avoid);
+ return {
+ hasChanges: styleNotes.changed || embrace.changed || avoid.changed,
+ styleNotes,
+ influences: { embrace, avoid },
+ };
+}
+
+export function buildStyleReferencePrompt({ title, prompt, styleNotes, influences, locked }) {
+ const context = JSON.stringify({
+ suppliedTitle: trimTo(title, STYLE_REFERENCE_TITLE_MAX) || null,
+ suppliedRecreationPrompt: trimTo(prompt, STYLE_REFERENCE_PROMPT_MAX) || null,
+ currentStyleNotes: trimTo(styleNotes, STYLE_NOTES_MAX),
+ currentGuidance: sanitizeInfluences(influences),
+ locked: sanitizeLocked(locked),
+ });
+ return `Analyze the attached image as an ART STYLE REFERENCE for a fictional-universe bible.
+
+Concentrate on renderable visual style: medium, line or brush treatment, shapes, texture, palette, lighting, composition, era, mood, and finish. Do not invent story facts, named characters, locations, or copyrighted-artist attribution. Produce guidance that could recreate the image's visual language while remaining generally reusable across subjects.
+
+Current universe context:
+${context}
+
+Return JSON only:
+{
+ "title": "short descriptive reference title (generate only when suppliedTitle is null)",
+ "prompt": "detailed image-generation prompt for recreating this image (generate only when suppliedRecreationPrompt is null)",
+ "styleNotes": "complete proposed replacement for currentStyleNotes",
+ "influences": {
+ "embrace": ["complete ordered positive style-token list"],
+ "avoid": ["complete ordered negative style-token list"]
+ },
+ "rationale": "one concise explanation of the proposed changes"
+}
+
+Honor every locked field: styleNotes, influencesEmbrace, or influencesAvoid must remain equivalent to the corresponding current value when locked. Preserve useful current guidance that does not conflict with the image. An empty array is a valid intentional recommendation.`;
+}
+
+export async function analyzeUniverseStyleReference({
+ imagePath,
+ imageFilename,
+ title,
+ prompt,
+ styleNotes,
+ influences,
+ locked,
+ providerId,
+ model,
+} = {}) {
+ if (!imagePath || !imageFilename) {
+ throw new ServerError('A gallery image is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const provider = await resolveAPIProvider(providerId);
+ assertProvider(provider, {
+ message: 'Analyzing an art reference needs an API-based provider with a vision-capable model. Configure one under Settings → Providers.',
+ code: 'NO_API_PROVIDER',
+ status: 503,
+ });
+ const result = await runPromptThroughProvider({
+ provider,
+ prompt: buildStyleReferencePrompt({ title, prompt, styleNotes, influences, locked }),
+ source: 'universe-style-reference',
+ model: model || undefined,
+ screenshots: [imagePath],
+ });
+ const ranProvider = assertVisionRunUsedImages(result, provider);
+ let parsed;
+ try {
+ parsed = parseLLMJSON(result.text || '');
+ } catch (error) {
+ throw new ServerError(`The vision model returned invalid style analysis: ${error.message}`, {
+ status: 502,
+ code: 'VISION_BAD_JSON',
+ });
+ }
+
+ const currentInfluences = sanitizeInfluences(influences);
+ const safeLocked = sanitizeLocked(locked);
+ const generatedTitle = trimTo(title, STYLE_REFERENCE_TITLE_MAX)
+ || trimTo(parsed?.title, STYLE_REFERENCE_TITLE_MAX)
+ || 'Art style reference';
+ const generatedPrompt = trimTo(prompt, STYLE_REFERENCE_PROMPT_MAX)
+ || trimTo(parsed?.prompt, STYLE_REFERENCE_PROMPT_MAX);
+ if (!generatedPrompt) {
+ throw new ServerError('The vision model returned no recreation prompt — try a different model or clearer image.', {
+ status: 502,
+ code: 'VISION_EMPTY',
+ });
+ }
+ const parsedInfluences = parsed?.influences && typeof parsed.influences === 'object'
+ ? parsed.influences
+ : {};
+ const proposed = {
+ styleNotes: safeLocked.styleNotes
+ ? trimTo(styleNotes, STYLE_NOTES_MAX)
+ : (typeof parsed?.styleNotes === 'string'
+ ? trimTo(parsed.styleNotes, STYLE_NOTES_MAX)
+ : trimTo(styleNotes, STYLE_NOTES_MAX)),
+ influences: {
+ embrace: safeLocked.influencesEmbrace
+ ? currentInfluences.embrace
+ : (Array.isArray(parsedInfluences.embrace)
+ ? sanitizeInfluences({ embrace: parsedInfluences.embrace }).embrace
+ : currentInfluences.embrace),
+ avoid: safeLocked.influencesAvoid
+ ? currentInfluences.avoid
+ : (Array.isArray(parsedInfluences.avoid)
+ ? sanitizeInfluences({ avoid: parsedInfluences.avoid }).avoid
+ : currentInfluences.avoid),
+ },
+ };
+
+ return {
+ reference: {
+ id: `style-ref-${randomUUID()}`,
+ title: generatedTitle,
+ prompt: generatedPrompt,
+ imageRefs: [imageFilename],
+ createdAt: new Date().toISOString(),
+ },
+ proposed,
+ diff: buildStyleReferenceDiff({ styleNotes, influences: currentInfluences }, proposed),
+ rationale: trimTo(parsed?.rationale, 1000),
+ llm: {
+ provider: ranProvider.id || provider.id,
+ model: result.model || null,
+ },
+ };
+}
+
+export const __testing = { buildStyleReferencePrompt, buildStyleReferenceDiff };
diff --git a/server/services/universeStyleReference.test.js b/server/services/universeStyleReference.test.js
new file mode 100644
index 0000000000..470679c210
--- /dev/null
+++ b/server/services/universeStyleReference.test.js
@@ -0,0 +1,150 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../lib/aiProvider.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, resolveAPIProvider: vi.fn() };
+});
+vi.mock('../lib/promptRunner.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, runPromptThroughProvider: vi.fn() };
+});
+
+const aiProvider = await import('../lib/aiProvider.js');
+const promptRunner = await import('../lib/promptRunner.js');
+const {
+ analyzeUniverseStyleReference,
+ buildStyleReferenceDiff,
+ buildStyleReferencePrompt,
+} = await import('./universeStyleReference.js');
+
+const apiProvider = { id: 'ollama', type: 'api', defaultModel: 'qwen-vl' };
+const analysisText = JSON.stringify({
+ title: 'Dust-lit ink wash',
+ prompt: 'A weathered city rendered in granular ink wash and muted ochre.',
+ styleNotes: 'Tactile ink-wash science fiction with restrained, dusty light.',
+ influences: {
+ embrace: ['granular ink wash', 'muted ochre', 'weathered silhouettes'],
+ avoid: ['glossy 3D', 'neon'],
+ },
+ rationale: 'The image replaces polish with tactile marks and restrained color.',
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ aiProvider.resolveAPIProvider.mockResolvedValue(apiProvider);
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: analysisText,
+ model: 'qwen-vl',
+ });
+});
+
+describe('universeStyleReference', () => {
+ it('analyzes the image and returns a reference plus a reviewable diff', async () => {
+ const result = await analyzeUniverseStyleReference({
+ imagePath: '/mock/images/reference.png',
+ imageFilename: 'reference.png',
+ styleNotes: 'Clean vector art',
+ influences: { embrace: ['clean vectors'], avoid: ['grain'] },
+ model: 'qwen-vl',
+ });
+
+ expect(result.reference).toMatchObject({
+ title: 'Dust-lit ink wash',
+ prompt: expect.stringContaining('granular ink wash'),
+ imageRefs: ['reference.png'],
+ });
+ expect(result.reference.id).toMatch(/^style-ref-/);
+ expect(result.diff).toMatchObject({
+ hasChanges: true,
+ influences: {
+ embrace: { added: ['granular ink wash', 'muted ochre', 'weathered silhouettes'], removed: ['clean vectors'] },
+ avoid: { added: ['glossy 3D', 'neon'], removed: ['grain'] },
+ },
+ });
+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledWith(
+ expect.objectContaining({
+ screenshots: ['/mock/images/reference.png'],
+ source: 'universe-style-reference',
+ }),
+ );
+ });
+
+ it('preserves user-supplied metadata and locked guidance', async () => {
+ const result = await analyzeUniverseStyleReference({
+ imagePath: '/mock/images/reference.png',
+ imageFilename: 'reference.png',
+ title: 'My title',
+ prompt: 'My exact recreation prompt',
+ styleNotes: 'Pinned prose',
+ influences: { embrace: ['pinned positive'], avoid: ['pinned negative'] },
+ locked: { styleNotes: true, influencesEmbrace: true, influencesAvoid: true },
+ });
+
+ expect(result.reference).toMatchObject({
+ title: 'My title',
+ prompt: 'My exact recreation prompt',
+ });
+ expect(result.proposed).toEqual({
+ styleNotes: 'Pinned prose',
+ influences: { embrace: ['pinned positive'], avoid: ['pinned negative'] },
+ });
+ expect(result.diff.hasChanges).toBe(false);
+ });
+
+ it('distinguishes an explicit empty recommendation from an omitted list', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify({
+ title: 'Reference',
+ prompt: 'Prompt',
+ styleNotes: 'Notes',
+ influences: { embrace: [] },
+ }),
+ });
+ const result = await analyzeUniverseStyleReference({
+ imagePath: '/mock/reference.png',
+ imageFilename: 'reference.png',
+ influences: { embrace: ['remove me'], avoid: ['preserve me'] },
+ });
+ expect(result.proposed.influences).toEqual({ embrace: [], avoid: ['preserve me'] });
+ });
+
+ it('rejects invalid JSON and vision runs that dropped the image', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValueOnce({ text: 'not json' });
+ await expect(analyzeUniverseStyleReference({
+ imagePath: '/mock/reference.png',
+ imageFilename: 'reference.png',
+ })).rejects.toMatchObject({ code: 'VISION_BAD_JSON', status: 502 });
+
+ promptRunner.runPromptThroughProvider.mockResolvedValueOnce({
+ text: analysisText,
+ provider: { id: 'cli-provider', type: 'cli' },
+ });
+ await expect(analyzeUniverseStyleReference({
+ imagePath: '/mock/reference.png',
+ imageFilename: 'reference.png',
+ })).rejects.toMatchObject({ code: 'VISION_FALLBACK_DROPPED_IMAGES', status: 502 });
+ });
+
+ it('builds deterministic list and prose diffs', () => {
+ expect(buildStyleReferenceDiff(
+ { styleNotes: 'before', influences: { embrace: ['A'], avoid: [] } },
+ { styleNotes: 'after', influences: { embrace: ['A', 'B'], avoid: [] } },
+ )).toMatchObject({
+ hasChanges: true,
+ styleNotes: { before: 'before', after: 'after', changed: true },
+ influences: { embrace: { added: ['B'], removed: [] } },
+ });
+ });
+
+ it('embeds supplied metadata and locks as JSON context', () => {
+ const prompt = buildStyleReferencePrompt({
+ title: 'Reference',
+ prompt: '',
+ styleNotes: 'Notes',
+ influences: { embrace: ['ink'], avoid: [] },
+ locked: { styleNotes: true },
+ });
+ expect(prompt).toContain('"suppliedTitle":"Reference"');
+ expect(prompt).toContain('"locked":{"styleNotes":true}');
+ });
+});